My user is uploading an image of any size XX x YY. I want to find the larger dimension and shrink the image to a square of 250x250 with transparent padding being added to make up the difference. Is there any way to accomplish this with CI's Image Lib?
Try this:
$config['image_library'] = 'gd2';
$config['source_image'] = '/path/to/image/mypic.jpg';
$config['maintain_ratio'] = TRUE;
$config['width'] = 250;
$config['height'] = 250;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$config['image_library'] = 'gd2';
$config['source_image'] = '/path/to/image/mypic.jpg';
$config['maintain_ratio'] = FALSE;
$config['width'] = 250;
$config['height'] = 250;
$this->image_lib->initialize($config);
$this->image_lib->crop();
For details, see the Image Manipulation Class from the CodeIgniter API
Although to be quite honest, I don't find CI's image manipulation library to be adequate. It isn't very flexible, it isn't very fast for repeated or combined actions (like the one above), and it uses an atrocious syntax (that may come in handy for certain types of applications, but I personally prefer something like PHP Thumb):
In fact, I recently put together a simple wrapper library for PHP Thumb (download) to use with CodeIgniter, and it works fabulously. Using the PHP Thumb library instead of CodeIgniter's own, you could get the job done like so:
$this->load->library('phpthumb_lib');
$thumb = phpthumb_lib::create('/path/to/image/mypic.jpg');
$thumb->adaptiveResize(250, 250);
$thumb->save();
More details on PHP Thumb's GitHub page.
Only this doesn't pad the image with transparent pixels (which I would consider a bad practice), it merely resizes and crops the image to fit the whole 250x250 pixel area without stretching the image.
Alternatively, you could make it resize the image to fit inside a 250x250 pixel box (by using resize
rather than adaptiveResize
), and then place the images inside 250x250px DIV containers. I'm guessing this is probably the solution you'll want.
I do not crop the image, rather place it in the background of a div. Here is my code.
1) Inside the helper place this.
function getSmallerDimension($img_path, $width, $height) {
list($wid, $hei, $type, $attr)= getimagesize($img_path);
$ratio = $wid / $hei;
if( $height < $width/$ratio ) {
return 'width';
}
else if( $width < $height * $ratio ) {
return 'height';
}
else {
return 'auto';
}
}
2) Use this to resize.
$config['image_library'] = 'gd2';
$config['source_image'] = 'source-path/source.jpg';
$config['create_thumb'] = true;
$config['thumb_marker'] = '-thumb';
$config['maintain_ratio'] = true;
$config['width'] = 250;
$config['height'] = 250;
$config['master_dim'] = getSmallerDimension('source-path/source.jpg', 250, 250);
$this->load->library('image_lib', $config);
$this->image_lib->resize();