get_width()
public function get_width(): int
Description
Returns the width in pixels of the currently loaded image. This method uses PHP's GD library imagesx() function to retrieve the width of the image resource.
Image Must Be Loaded: This method requires an image to be loaded first using load() or upload(). Calling get_width() without a loaded image will throw an Exception with the message "No image is loaded."
Parameters
This method takes no parameters.
Return Value
| Type |
Description |
| int |
The width of the loaded image in pixels. |
Example #1
The code sample below demonstrates the most basic use of get_width().
// Load an image
$this->image->load('modules/gallery/photos/photo.jpg');
// Get the width
$width = $this->image->get_width();
echo $width; // Outputs: 1920 (for example)
Common Use Cases: The get_width() method is typically used to determine aspect ratios, validate image dimensions, calculate resize operations, or make decisions about how to process an image based on its dimensions.
Example #2
The example above shows how to validate image width before processing.
public function process_product_image(): void {
$product_id = segment(3, 'int');
// Validate file upload
$this->validation->set_rules('userfile', 'Product Image', 'required|allowed_types[jpg,png]|max_size[5000]');
if ($this->validation->run() === true) {
// Configure upload
$config = [
'destination' => 'products/temp',
'upload_to_module' => true,
'make_rand_name' => true
];
// Ensure temp directory exists
$temp_dir = 'modules/products/products/temp';
if (!$this->file->exists($temp_dir)) {
$this->file->create_directory($temp_dir, 0755);
}
// Upload the image
$file_info = $this->image->upload($config);
// Load to check dimensions
$this->image->load($file_info['file_path']);
$width = $this->image->get_width();
$height = $this->image->get_height();
// Validate minimum dimensions
if ($width < 800 || $height < 600) {
// Delete invalid upload
$this->file->delete($file_info['file_path']);
$this->image->destroy();
set_flashdata('Product images must be at least 800x600 pixels. Your image was ' . $width . 'x' . $height);
redirect('products/upload_image/' . $product_id);
}
// Dimensions are valid - process the image
$this->image->resize_to_width(800);
// Save to permanent location
$output_path = 'modules/products/products/images/' . $file_info['file_name'];
// Ensure directory exists
if (!$this->file->exists('modules/products/products/images')) {
$this->file->create_directory('modules/products/products/images', 0755);
}
$this->image->save($output_path, 85);
// Delete temp file
$this->file->delete($file_info['file_path']);
$this->image->destroy();
// Update product record
$data = [
'image_filename' => $file_info['file_name'],
'image_width' => 800,
'image_height' => $this->image->get_height()
];
$this->model->update($product_id, $data, 'products');
set_flashdata('Product image uploaded successfully');
redirect('products/manage');
} else {
$this->upload_form($product_id);
}
}
Minimum Dimension Validation: Use get_width() and get_height() to enforce minimum dimension requirements. Upload to a temporary location first, validate dimensions, then move to permanent storage only if valid. This prevents poor-quality images from entering your system.
Example #3
The example above demonstrates using get_width() to determine the optimal resize strategy.
public function create_responsive_sizes(): void {
$image_id = segment(3, 'int');
// Get image record
$image = $this->db->get_where($image_id, 'gallery_images');
if ($image === false) {
redirect('gallery/not_found');
}
$source_path = 'modules/gallery/originals/' . $image->filename;
if (!$this->file->exists($source_path)) {
redirect('gallery/file_missing');
}
// Load the source image
$this->image->load($source_path);
// Get current width
$current_width = $this->image->get_width();
// Define responsive breakpoints (only create if source is larger)
$breakpoints = [
'xlarge' => 1920,
'large' => 1200,
'medium' => 800,
'small' => 480
];
foreach ($breakpoints as $size_name => $target_width) {
// Only create this size if source is larger
if ($current_width > $target_width) {
// Load source fresh for each size
$this->image->load($source_path);
// Resize to target width
$this->image->resize_to_width($target_width);
// Save the responsive version
$output_dir = 'modules/gallery/' . $size_name;
if (!$this->file->exists($output_dir)) {
$this->file->create_directory($output_dir, 0755);
}
$output_path = $output_dir . '/' . $image->filename;
$this->image->save($output_path, 85);
// Free memory
$this->image->destroy();
}
}
set_flashdata('Responsive image sizes generated');
redirect('gallery/view/' . $image_id);
}
Responsive Image Generation: Check the source width with get_width() before creating responsive sizes. Only generate smaller versions if the source is actually larger than the target. This prevents unnecessary upscaling and maintains image quality.
Example #4
The example above shows using get_width() to calculate proportional crop dimensions.
public function create_proportional_thumbnail(): void {
$photo_id = segment(3, 'int');
// Get photo record
$photo = $this->db->get_where($photo_id, 'photos');
if ($photo === false) {
redirect('photos/not_found');
}
$source_path = 'modules/gallery/photos/' . $photo->filename;
if (!$this->file->exists($source_path)) {
redirect('photos/file_missing');
}
// Load the image
$this->image->load($source_path);
// Get dimensions
$width = $this->image->get_width();
$height = $this->image->get_height();
// Target thumbnail dimensions
$thumb_size = 300;
// Calculate aspect ratio
$aspect_ratio = $width / $height;
// Determine crop dimensions based on aspect ratio
if ($aspect_ratio > 1) {
// Landscape: resize based on height, then crop width
$resize_height = $thumb_size;
$resize_width = (int)($thumb_size * $aspect_ratio);
$this->image->resize_to_height($resize_height);
$this->image->crop($thumb_size, $thumb_size, 'center');
} elseif ($aspect_ratio < 1) {
// Portrait: resize based on width, then crop height
$resize_width = $thumb_size;
$resize_height = (int)($thumb_size / $aspect_ratio);
$this->image->resize_to_width($resize_width);
$this->image->crop($thumb_size, $thumb_size, 'center');
} else {
// Square: simple resize
$this->image->resize_to_width($thumb_size);
}
// Save thumbnail
$thumb_dir = 'modules/gallery/photos/thumbs';
if (!$this->file->exists($thumb_dir)) {
$this->file->create_directory($thumb_dir, 0755);
}
$thumb_path = $thumb_dir . '/' . $photo->filename;
$this->image->save($thumb_path, 85);
$this->image->destroy();
// Update photo record
$update_data = [
'thumbnail_path' => $thumb_path,
'thumbnail_created_at' => date('Y-m-d H:i:s')
];
$this->model->update($photo_id, $update_data, 'photos');
set_flashdata('Thumbnail created successfully');
redirect('gallery/view/' . $photo_id);
}
Aspect Ratio Calculations: Use get_width() and get_height() together to calculate aspect ratios and make intelligent processing decisions. This allows you to apply different strategies for landscape, portrait, and square images, ensuring optimal results for all orientations.