resize_to_width()

public function resize_to_width(int $width): void

Description

Resizes a loaded image to the specified width whilst automatically calculating and maintaining the correct height to preserve the original aspect ratio. This method ensures proportional scaling with no distortion.

Load First, Then Resize: This method requires an image to be loaded first using load() or upload(). Calling resize_to_width() without a loaded image will throw an Exception with the message "No image is loaded to resize."

Parameters

Parameter Type Description Default Required
$width int The target width in pixels. Must be greater than zero. N/A Yes

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_to_width().

PHP
// Load an image
$this->image->load('modules/gallery/photos/photo.jpg');

// Resize to 800 pixels wide (height calculated automatically)
$this->image->resize_to_width(800);

// Save the resized image
$this->image->save('modules/gallery/photos/photo_resized.jpg');

Aspect Ratio Preservation: The resize_to_width() method automatically calculates the proportional height needed to maintain the original aspect ratio. You only specify the width - the height adjusts accordingly, ensuring no distortion or stretching of the image.

Example #2

The example above shows how to standardise product images to a consistent width.

PHP
public function standardise_product_images(): void {
    // Get all products with images
    $products = $this->model->get_many_where('image_filename IS NOT NULL', 'products');
    
    if ($products === false) {
        redirect('products/manage');
    }
    
    $target_width = 600;
    $processed = 0;
    
    foreach ($products as $product) {
        $source_path = 'modules/products/images/' . $product->image_filename;
        
        if ($this->file->exists($source_path)) {
            // Load the product image
            $this->image->load($source_path);
            
            // Only resize if wider than target
            if ($this->image->get_width() > $target_width) {
                $this->image->resize_to_width($target_width);
                
                // Ensure standardised directory exists
                if (!$this->file->exists('modules/products/images/standard')) {
                    $this->file->create_directory('modules/products/images/standard', 0755);
                }
                
                // Save the standardised version
                $output_path = 'modules/products/images/standard/' . $product->image_filename;
                $this->image->save($output_path, 85);
                $processed++;
            }
            
            $this->image->destroy();
        }
    }
    
    set_flashdata("Standardised {$processed} product images to {$target_width}px width");
    redirect('products/manage');
}

Batch Processing Pattern: When standardising multiple images to a consistent width, always call destroy() at the end of each iteration to free memory. Check the current width before resizing to avoid unnecessary processing of images that are already smaller than the target width.

Example #3

The example above demonstrates creating responsive image sizes for different screen widths.

PHP
public function generate_responsive_images(): 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/originals/' . $photo->filename;
    
    if (!$this->file->exists($source_path)) {
        redirect('photos/file_missing');
    }
    
    // Define responsive breakpoints
    $breakpoints = [
        'mobile' => 480,
        'tablet' => 768,
        'desktop' => 1200,
        'large' => 1920
    ];
    
    // Check source width
    $this->image->load($source_path);
    $source_width = $this->image->get_width();
    $this->image->destroy();
    
    foreach ($breakpoints as $device => $target_width) {
        // Only create this size if source is wider
        if ($source_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);
            
            // Ensure device directory exists
            $output_dir = 'modules/gallery/responsive/' . $device;
            if (!$this->file->exists($output_dir)) {
                $this->file->create_directory($output_dir, 0755);
            }
            
            // Save the responsive version
            $output_path = $output_dir . '/' . $photo->filename;
            $this->image->save($output_path, 85);
            $this->image->destroy();
        }
    }
    
    set_flashdata('Responsive image sizes generated successfully');
    redirect('gallery/view/' . $photo_id);
}

Responsive Images Pattern: Generate multiple width variations from a single high-resolution source. Only create smaller versions when the source is actually wider than the target, preventing unnecessary upscaling. This approach enables modern responsive image techniques using <picture> elements or srcset attributes.

Example #4

The example above shows dynamically serving images resized to user-specified widths.

PHP
public function serve_dynamic_width(): void {
    $photo_id = segment(3, 'int');
    $requested_width = segment(4, 'int');
    
    // Validate width parameter
    if ($requested_width < 100 || $requested_width > 2000) {
        redirect('photos/invalid_width');
    }
    
    // Get photo record
    $photo = $this->db->get_where($photo_id, 'photos');
    
    if ($photo === false) {
        redirect('photos/not_found');
    }
    
    $source_path = 'modules/gallery/originals/' . $photo->filename;
    
    if (!$this->file->exists($source_path)) {
        redirect('photos/file_missing');
    }
    
    // Load the source image
    $this->image->load($source_path);
    
    // Get source width
    $source_width = $this->image->get_width();
    
    // Only resize if requested width is smaller
    if ($requested_width < $source_width) {
        $this->image->resize_to_width($requested_width);
    }
    
    // Set appropriate headers
    header('Content-Type: ' . $this->image->get_header());
    header('Cache-Control: public, max-age=86400');
    header('Content-Disposition: inline; filename="' . $photo->filename . '"');
    
    // Output the image
    $this->image->output();
    $this->image->destroy();
}

Dynamic Width Serving: Create a controller method that accepts width as a URL parameter, enabling on-the-fly image resizing. This is useful for content delivery networks (CDNs), responsive image serving, or allowing users to download images in specific sizes. Always validate the requested width and add cache headers for performance.

Performance Consideration: When using resize_to_width() in loops or for dynamic serving, consider caching the resized versions to disk rather than processing on every request. For high-traffic applications, pre-generate common sizes during upload rather than resizing dynamically.