crop()
public function crop(int $width, int $height, string $trim = 'center'): void
Description
Crops a loaded image to the specified dimensions. The method extracts a portion of the current image based on the provided width, height, and trim position, then replaces the loaded image with the cropped version.
Load First, Then Crop: This method requires an image to be loaded first using load() or upload(). Calling crop() without a loaded image will result in an error.
Parameters
| Parameter |
Type |
Description |
Default |
Required |
| $width |
int |
The desired width of the cropped image in pixels. |
N/A |
Yes |
| $height |
int |
The desired height of the cropped image in pixels. |
N/A |
Yes |
| $trim |
string |
Determines which part of the image to keep. Options: 'left', 'center', 'right'. |
'center' |
No |
Understanding the Trim Parameter
The $trim parameter controls which portion of the image is preserved when cropping to dimensions smaller than the original:
- 'left': Crops from the top-left corner, preserving the left side of the image
- 'center': (default) Crops from the center, preserving the middle portion of the image
- 'right': Crops from the top-right corner, preserving the right side of the image
How Trim Works: When the crop dimensions are smaller than the current image, crop() calculates the offset to determine which pixels to extract. For 'center' trim, the offset is half the difference between current and target dimensions. For 'right' trim, the offset is the full difference. For 'left' trim, there is no offset (starts at 0,0).
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 image cropping operation.
// Load an image
$this->image->load('modules/gallery/photos/landscape.jpg');
// Crop to 400x400 pixels from center
$this->image->crop(400, 400);
// Save the cropped image
$this->image->save('modules/gallery/photos/landscape_cropped.jpg');
The Stateful Workflow: The Image module follows a load → manipulate → save pattern. Always load an image first with load(), then apply operations like crop(), and finally either save() to disk or output() to the browser. Each operation modifies the internal image resource, so operations are cumulative.
Example #2
The example above shows how to create a square profile picture by cropping an uploaded image.
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 for cropping
$this->image->load($file_info['file_path']);
// Crop to perfect square (300x300) from center
$this->image->crop(300, 300, 'center');
// Save the cropped version
$this->image->save($file_info['file_path'], 85);
// 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);
}
}
Example #3
The example above demonstrates creating multiple crop variations with different trim positions.
public function generate_product_previews(): 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/images/' . $product->main_image;
if (!$this->file->exists($source_image)) {
redirect('products/image_not_found');
}
// Define crop variations for different display contexts
$crop_configs = [
'square' => ['width' => 400, 'height' => 400, 'trim' => 'center'],
'wide' => ['width' => 600, 'height' => 400, 'trim' => 'center'],
'tall' => ['width' => 300, 'height' => 500, 'trim' => 'left']
];
foreach ($crop_configs as $variant => $config) {
// Load source image for each variation
$this->image->load($source_image);
// Apply crop
$this->image->crop($config['width'], $config['height'], $config['trim']);
// Save with descriptive filename
$output_path = 'modules/products/images/preview_' . $variant . '_' . $product->main_image;
$this->image->save($output_path, 85);
}
set_flashdata('Product preview images generated successfully');
redirect('products/manage/' . $product_id);
}
Multiple Operations on Same Source: When creating multiple variations from one source image, load the original image fresh before each operation. Image operations are cumulative - if you crop once and then crop again, the second crop operates on the already-cropped image, not the original.
Example #4
The example above shows combining resize and crop operations to create a thumbnail with exact dimensions.
public function create_gallery_thumbnail(): void {
$photo_id = segment(3, 'int');
// Get photo record
$photo = $this->db->get_where($photo_id, 'gallery_photos');
if ($photo === false) {
redirect('gallery/not_found');
}
$source_path = 'modules/gallery/uploads/' . $photo->filename;
if (!$this->file->exists($source_path)) {
redirect('gallery/file_missing');
}
// Load the source image
$this->image->load($source_path);
// Get current dimensions
$current_width = $this->image->get_width();
$current_height = $this->image->get_height();
// Target thumbnail dimensions
$thumb_width = 200;
$thumb_height = 200;
// Calculate aspect ratios
$source_ratio = $current_width / $current_height;
$target_ratio = $thumb_width / $thumb_height;
// Resize to ensure the image is at least as large as target dimensions
if ($source_ratio > $target_ratio) {
// Image is wider - resize based on height
$this->image->resize_to_height($thumb_height);
} else {
// Image is taller or square - resize based on width
$this->image->resize_to_width($thumb_width);
}
// Now crop to exact dimensions from center
$this->image->crop($thumb_width, $thumb_height, 'center');
// Save thumbnail
$thumb_path = 'modules/gallery/uploads/thumbs/' . $photo->filename;
// Ensure thumbnail directory exists
if (!$this->file->exists('modules/gallery/uploads/thumbs')) {
$this->file->create_directory('modules/gallery/uploads/thumbs', 0755);
}
$this->image->save($thumb_path, 85);
// Update photo record with thumbnail path
$update_data = [
'thumbnail_path' => $thumb_path,
'thumbnail_generated_at' => date('Y-m-d H:i:s')
];
$this->model->update($photo_id, $update_data, 'gallery_photos');
set_flashdata('Thumbnail generated successfully');
redirect('gallery/view/' . $photo_id);
}
Resize Then Crop Pattern: For perfect thumbnails with exact dimensions, use the resize-then-crop pattern. First resize the image so its smallest dimension matches your target (using resize_to_width() or resize_to_height()), then crop to exact dimensions. This ensures no distortion while filling the target area completely.