Asfihani Dicatet Ben Ora Lali™ (literally mean: dicatat biar tidak lupa)

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 '<img src="/images/earth_thumb.jpg" alt="" />';
}

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-&gt;load-&gt;library('simple_image');
$this-&gt;simple_image&gt;load(FCPATH .'images/earth.jpg');
$this-&gt;simple_image-&gt;resizeToWidth(128);
$this-&gt;simple_image-&gt;save(FCPATH .'images/earth_thumb.jpg');
 
if ( file_exists(FCPATH .'images/earth_thumb.jpg'))
{
	echo '<img src="/images/earth_thumb.jpg" alt="" />';
}

The code render image with correct size :

earth_thumb2

Image source: http://twitrounds.com/

Random Posts:




No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment