The image library has given me a lot of headaches -- not because it's bad, but because I have to relearn how it works every time I try to do something new with it. For me at least, the documentation is a little hard to understand.
In the beginning, I also thought that it made more sense to resize before cropping. I don't remember exactly why, but I later found it was better to do the opposite. I may be mistaken on that, but my code works fine now, so I'm going to stick with that strategy.
Another thing that I think is important is setting the 'maintain_ratio' to FALSE and doing the calculations myself.
I recently rewrote my function for resizing, and I think it's mostly self-explanatory, except for my variable $top_crop. That's my "barber" variable, which tries to assume how much to take off the top. In my configuration file 'settings,' I have it set to 20. That means that out of the total amount to be cropped, take 20% off the top. In other words, if you're cropping 100px, take 20 from the top and 80 from the bottom.
Anyway, here's my code for cropping. You can use it and adapt it to your needs:
function resize_img($data){
if ($data['width'] == 0 || $data['height'] == 0){
return FALSE;
}
$this->config->load('settings');
$ratio = $data['height']/$data['width'];
$targ_ratio = $data['max_ht']/$data['max_wd'];
$top_crop = $this->config->item('crop_top');
if ($targ_ratio >= $ratio){
//too wide
$crop_width = floor($data['height'] / $targ_ratio);
$crop_height = $data['height'];
} else {
//too tall
$crop_width = $data['width'];
$crop_height = floor($data['width'] * $targ_ratio);
}
$img_data = array( 'source_image' => $data['full_path'],
'maintain_ratio' => FALSE,
'x_axis' => round(($data['width'] - $crop_width)/2),
'y_axis' => round(($data['height'] - $crop_height)*$top_crop/100),
'width' => $crop_width,
'height' => $crop_height);
//thumbs have a target path
if ($data['target_path']){
$img_data['new_image'] = $data['target_path'];
//set source for the crop, because for thumbs it will be the thumb folder
$source = $data['target_path'].$data['file_name'];
} else {
$source = $data['full_path'];
}
$this->image_lib->clear();
$this->image_lib->initialize($img_data);
if ($this->image_lib->crop()){
$img_data = array( 'source_image' => $source,
'maintain_ratio' => FALSE,
'width' => $data['max_wd'],
'height' => $data['max_ht']);
$this->image_lib->clear();
$this->image_lib->initialize($img_data);
if($this->image_lib->resize()){
return array('height' => $data['max_ht'], 'width' => $data['max_wd']);
}
}
return $this->image_lib->display_errors();
}