CodeIgniter: resizing image using SimpleImage

ci_logo2The CodeIgniter (CI) framework is powerfull tool for rapid PHP application development. It has a lot of ready to use libraries and helpers. For example the Image Manipulation library resize function that lets you resize the original image, create a copy (with or without resizing), or create a thumbnail image. But, there is a minor problem when resize image with main ratio enabled. For example, if you want to resize an 256px x256px earth images below to 128px x 128px.

earth

The snippet Controller code :

$config['image_library'] = 'gd2';
$config['source_image'] = FCPATH .'images/earth.jpg';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 128;

$this->load->library('image_lib', $config);
$this->image_lib->resize();

if ( file_exists(FCPATH .'images/earth_thumb.jpg'))
{
	echo '';
}

The result is 128px x 256px image :

earth_thumb

Not as expected…until you have specified $config[‘height’] value :) like $config[‘height’] = 128 :)

Alternatively, there is excellent class called SimpleImage by Simon Jarvis. We can use this class as library in CodeIgniter. First, create file Simple_image.php inside system/application/libraries/ directory and paste the code from above link. After php tags add :

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Modify :

class SimpleImage {

To :

class Simple_image {

Dont forget to remove php closing tag (?>) at the end of the file as stated here. And let’s call the library inside the code :

$this->load->library('simple_image');
$this->simple_image>load(FCPATH .'images/earth.jpg');
$this->simple_image->resizeToWidth(128);
$this->simple_image->save(FCPATH .'images/earth_thumb.jpg');

if ( file_exists(FCPATH .'images/earth_thumb.jpg'))
{
	echo '';
}

The code render image with correct size :

earth_thumb2

Image source: http://twitrounds.com/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.