resize_and_crop()
public function resize_and_crop(int $width, int $height): void
Description
Resizes and crops a loaded image to exact dimensions in a single operation. This method intelligently determines the optimal resize strategy based on aspect ratios, then crops to achieve the target dimensions precisely. The result is an image that exactly matches the specified width and height with no distortion.
Load First, Then Process: This method requires an image to be loaded first using load() or upload(). Calling resize_and_crop() without a loaded image will throw an Exception with the message "No image is loaded to resize and crop."
Parameters
| Parameter |
Type |
Description |
Default |
Required |
| $width |
int |
The target width in pixels. |
N/A |
Yes |
| $height |
int |
The target height in pixels. |
N/A |
Yes |
How It Works
The resize_and_crop() method automatically calculates the optimal strategy based on aspect ratios:
- If aspect ratios match: Simply resizes to target dimensions
- If target is wider: Resizes to target width, then crops height from centre
- If target is taller: Resizes to target height, then crops width from centre
This intelligent approach ensures the image fills the target dimensions completely with minimal cropping, preserving as much of the original image as possible whilst maintaining the exact size requirements.
Single Operation Convenience: The resize_and_crop() method combines what would otherwise require separate resize_to_width()/resize_to_height() and crop() calls. It's particularly useful when you need images to be exactly a certain size, such as thumbnails, profile pictures, or grid layouts.
Return Value
| Type |
Description |
| void |
This method does not return a value. It modifies the loaded image resource in place. |
Example #1
The code sample below demonstrates the most basic use of resize_and_crop().
// Load an image
$this->image->load('modules/gallery/photos/photo.jpg');
// Resize and crop to exact 400x400 square
$this->image->resize_and_crop(400, 400);
// Save the result
$this->image->save('modules/gallery/photos/photo_thumb.jpg');
Perfect Thumbnails Pattern: The resize_and_crop() method is ideal for creating thumbnails that must be exact dimensions. Unlike simple resizing (which may produce varied sizes) or manual resize-then-crop sequences, this single method guarantees precise dimensions with optimal cropping.
Example #2
The example above shows how to create uniform profile avatars from uploaded images.
public function process_avatar(): void {
$user_id = segment(3, 'int');
// Validate image upload
$this->validation->set_rules('userfile', 'Profile Picture', 'required|allowed_types[jpg,png,gif]|max_size[5000]');
if ($this->validation->run() === true) {
// Configure upload
$config = [
'destination' => 'avatars',
'upload_to_module' => true,
'target_module' => 'users',
'make_rand_name' => true
];
// Ensure destination exists
$avatar_dir = 'modules/users/avatars';
if (!$this->file->exists($avatar_dir)) {
$this->file->create_directory($avatar_dir, 0755);
}
// Upload the image
$file_info = $this->image->upload($config);
// Load the uploaded image
$this->image->load($file_info['file_path']);
// Create perfect 200x200 avatar (works with any source aspect ratio)
$this->image->resize_and_crop(200, 200);
// Save the processed avatar
$this->image->save($file_info['file_path'], 85);
$this->image->destroy();
// Update user record
$data = [
'avatar_filename' => $file_info['file_name'],
'avatar_updated_at' => date('Y-m-d H:i:s')
];
$this->model->update($user_id, $data, 'users');
set_flashdata('Profile picture updated successfully');
redirect('users/profile/' . $user_id);
} else {
$this->avatar_upload_form($user_id);
}
}
Consistent Display Sizes: Using resize_and_crop() ensures all avatars, thumbnails, or grid images have identical dimensions regardless of the original image's aspect ratio. This creates clean, uniform layouts without the need for CSS tricks or complex frontend code.
Example #3
The example above demonstrates creating multiple standard sizes for a product gallery.
public function generate_product_images(): void {
$product_id = segment(3, 'int');
// Get product record
$product = $this->db->get_where($product_id, 'products');
if ($product === false) {
redirect('products/not_found');
}
$source_image = 'modules/products/originals/' . $product->original_filename;
if (!$this->file->exists($source_image)) {
redirect('products/image_missing');
}
// Define standard product image sizes
$sizes = [
'thumbnail' => ['width' => 150, 'height' => 150],
'grid' => ['width' => 300, 'height' => 300],
'detail' => ['width' => 600, 'height' => 600],
'hero' => ['width' => 1200, 'height' => 800]
];
foreach ($sizes as $size_name => $dimensions) {
// Load source fresh for each size
$this->image->load($source_image);
// Resize and crop to exact dimensions
$this->image->resize_and_crop($dimensions['width'], $dimensions['height']);
// Ensure directory exists
$output_dir = 'modules/products/images/' . $size_name;
if (!$this->file->exists($output_dir)) {
$this->file->create_directory($output_dir, 0755);
}
// Save the sized version
$output_path = $output_dir . '/' . $product->original_filename;
$this->image->save($output_path, 85);
$this->image->destroy();
}
set_flashdata('Product images generated successfully');
redirect('products/manage/' . $product_id);
}
Multi-Size Generation Pattern: When creating multiple size variations, resize_and_crop() simplifies the process significantly. Each size is guaranteed to match specifications exactly, making responsive image delivery predictable and layouts consistent across all devices.
Example #4
The example above shows creating social media sharing images with platform-specific dimensions.
public function generate_social_images(): void {
$article_id = segment(3, 'int');
// Get article record
$article = $this->db->get_where($article_id, 'articles');
if ($article === false) {
redirect('articles/not_found');
}
$featured_image = 'modules/articles/images/' . $article->featured_image;
if (!$this->file->exists($featured_image)) {
redirect('articles/image_missing');
}
// Define social media platform requirements
$social_specs = [
'facebook' => ['width' => 1200, 'height' => 630],
'twitter' => ['width' => 1200, 'height' => 675],
'instagram' => ['width' => 1080, 'height' => 1080],
'linkedin' => ['width' => 1200, 'height' => 627],
'pinterest' => ['width' => 1000, 'height' => 1500]
];
$social_dir = 'modules/articles/social';
if (!$this->file->exists($social_dir)) {
$this->file->create_directory($social_dir, 0755);
}
foreach ($social_specs as $platform => $dimensions) {
// Load source image
$this->image->load($featured_image);
// Create platform-specific version
$this->image->resize_and_crop($dimensions['width'], $dimensions['height']);
// Save with platform name
$filename_parts = pathinfo($article->featured_image);
$social_filename = $filename_parts['filename'] . '_' . $platform . '.' . $filename_parts['extension'];
$output_path = $social_dir . '/' . $social_filename;
$this->image->save($output_path, 85);
$this->image->destroy();
}
// Update article record with social image flag
$update_data = ['social_images_generated' => 1];
$this->model->update($article_id, $update_data, 'articles');
set_flashdata('Social media images generated for all platforms');
redirect('articles/edit/' . $article_id);
}
Platform-Specific Images: Different social media platforms require different image dimensions for optimal display. The resize_and_crop() method makes it straightforward to generate properly sized images for Facebook, Twitter, Instagram, LinkedIn, Pinterest, and other platforms from a single source image.