load()
public function load(string $filename): void
Description
Loads an existing image file into memory for processing. This method performs comprehensive security validation before loading, including MIME type verification, file signature checking, malicious content scanning, and memory requirement calculations. Once loaded, the image is ready for manipulation operations such as resizing, cropping, or scaling.
Security by Design: The load() method automatically validates images through four security layers: MIME type verification, file signature validation, script injection prevention, and memory limit enforcement. These checks cannot be bypassed and ensure only legitimate image files are processed.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| $filename | string | The filesystem path to the image file. Use relative paths from application root (e.g., 'modules/products/images/laptop.jpg'). | N/A | Yes |
Two Ways to Load Images
The Image module provides two valid patterns for loading images into memory:
Pattern 1: Via Trongate Module Loading (Recommended)
Use $this->image->load() in your controllers - this follows standard Trongate conventions:
$this->image->load('path/to/image.jpg');
$this->image->resize_to_width(800);
$this->image->save('output.jpg');Pattern 2: Via Constructor (Standalone)
Create a new Image instance directly - useful for standalone scripts or when you need multiple independent image processors:
$image = new Image('path/to/image.jpg');
$image->resize_to_width(800);
$image->save('output.jpg');Both patterns work identically. The constructor simply calls load() internally as a convenience. Use Pattern 1 in Trongate controllers and Pattern 2 in standalone contexts.
Supported Formats
The load() method automatically detects and handles the following image formats:
- JPEG (.jpg, .jpeg) - Most common web format
- PNG (.png) - Supports transparency
- GIF (.gif) - Supports animation and transparency
- WEBP (.webp) - Modern format with excellent compression
Path Type Matters: Use filesystem paths with load(), not URLs. Correct: 'modules/shop/products/widget.jpg' or '../modules/shop/products/widget.jpg'. Incorrect: 'shop_module/products/widget.jpg' (that's a URL pattern for browser display, not filesystem access).
Return Value
| Type | Description |
|---|---|
| void | This method does not return a value. It loads the image into memory, making it available for subsequent processing operations. |
Example #1
The code sample below demonstrates the most basic use of load().
// Load an existing image
$this->image->load('modules/gallery/photos/landscape.jpg');
// Resize it
$this->image->resize_to_width(800);
// Save the result
$this->image->save('modules/gallery/photos/landscape_800.jpg');The Load-Process-Save Pattern: This three-step workflow is fundamental to the Image module: (1) load() brings an image into memory, (2) processing methods like resize_to_width() or crop() modify it, and (3) save() writes the result to disk. This stateful approach ensures you always know what image you're working with.
Example #2
The example above shows how to load and process an image within a controller method.
public function create_thumbnail(): void {
$product_id = segment(3, 'int');
// Get product record
$product = $this->db->get_where($product_id, 'products');
if ($product === false) {
redirect('products/not_found');
}
// Check if the image file exists
if (!$this->file->exists($product->image_path)) {
set_flashdata('Product image file not found');
redirect('products/manage/' . $product_id);
}
// Load the product image from database path
$this->image->load($product->image_path);
// Create thumbnail
$this->image->resize_and_crop(300, 300);
// Save thumbnail
$thumbnail_path = 'modules/products/thumbnails/' . basename($product->image_path);
$this->image->save($thumbnail_path, 85);
$this->image->destroy();
// Update product record with thumbnail path
$update_data = ['thumbnail_path' => $thumbnail_path];
$this->model->update($product_id, $update_data, 'products');
set_flashdata('Thumbnail created successfully');
redirect('products/manage/' . $product_id);
}Check Before You Load: Always verify files exist using $this->file->exists() before attempting to load them. This prevents exceptions and allows you to handle missing files gracefully with appropriate user feedback or fallback behavior.
Example #3
The example above demonstrates generating multiple sizes from a single source image.
public function generate_responsive_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');
}
$source_image = 'modules/articles/originals/' . $article->original_filename;
if (!$this->file->exists($source_image)) {
set_flashdata('Original image not found');
redirect('articles/edit/' . $article_id);
}
// Define responsive breakpoints
$sizes = [
'mobile' => 480,
'tablet' => 768,
'desktop' => 1024,
'large' => 1440
];
// Ensure output directories exist
foreach (array_keys($sizes) as $size_name) {
$output_dir = 'modules/articles/images/' . $size_name;
if (!$this->file->exists($output_dir)) {
$this->file->create_directory($output_dir, 0755);
}
}
$generated_paths = [];
foreach ($sizes as $size_name => $width) {
// Load source fresh for each size
$this->image->load($source_image);
// Only resize if source is larger than target
if ($this->image->get_width() > $width) {
$this->image->resize_to_width($width);
}
// Save this size variant
$output_path = 'modules/articles/images/' . $size_name . '/' . $article->original_filename;
$this->image->save($output_path, 85);
$this->image->destroy();
$generated_paths[$size_name] = $output_path;
}
// Update article with all generated paths
$update_data = [
'image_mobile' => $generated_paths['mobile'],
'image_tablet' => $generated_paths['tablet'],
'image_desktop' => $generated_paths['desktop'],
'image_large' => $generated_paths['large']
];
$this->model->update($article_id, $update_data, 'articles');
set_flashdata('Responsive images generated successfully');
redirect('articles/edit/' . $article_id);
}Reload for Multiple Operations: When generating multiple versions of an image, call load() fresh for each variant. This ensures each version starts from the original source rather than being processed from an already-modified image, preventing cumulative quality loss or unwanted transformations.
Example #4
The example above shows advanced conditional image processing based on dimensions and orientation.
public function optimize_batch_uploads(): void {
$batch_id = segment(3, 'int');
// Get all uploads in this batch
$uploads = $this->model->get_many_where('batch_id', $batch_id, 'user_uploads');
if (count($uploads) === 0) {
set_flashdata('No uploads found in this batch');
redirect('uploads/batches');
}
$processed_count = 0;
$max_dimension = 2000;
// Ensure all required directories exist
$directories = ['images', 'thumbnails', 'portraits', 'landscapes'];
foreach ($directories as $dir) {
$path = 'modules/uploads/' . $dir;
if (!$this->file->exists($path)) {
$this->file->create_directory($path, 0755);
}
}
foreach ($uploads as $upload) {
$temp_path = 'modules/uploads/temp/' . $upload->temp_filename;
if (!$this->file->exists($temp_path)) {
continue;
}
// Load the uploaded image
$this->image->load($temp_path);
// Get dimensions and calculate aspect ratio
$width = $this->image->get_width();
$height = $this->image->get_height();
$aspect_ratio = $width / $height;
// Determine orientation
$is_portrait = $aspect_ratio < 1;
$is_landscape = $aspect_ratio > 1;
$is_square = abs($aspect_ratio - 1) < 0.01;
// Resize if needed
if ($width > $max_dimension || $height > $max_dimension) {
if ($width > $height) {
$this->image->resize_to_width($max_dimension);
} else {
$this->image->resize_to_height($max_dimension);
}
}
// Save to orientation-specific directory
$subdir = $is_portrait ? 'portraits' : ($is_landscape ? 'landscapes' : 'images');
$final_path = 'modules/uploads/' . $subdir . '/' . $upload->temp_filename;
$this->image->save($final_path, 85);
// Generate thumbnail (reload for fresh processing)
$this->image->load($temp_path);
$this->image->resize_and_crop(200, 200);
$thumb_path = 'modules/uploads/thumbnails/' . $upload->temp_filename;
$this->image->save($thumb_path, 80);
$this->image->destroy();
// Update upload record
$update_data = [
'final_path' => $final_path,
'thumbnail_path' => $thumb_path,
'orientation' => $is_portrait ? 'portrait' : ($is_landscape ? 'landscape' : 'square'),
'aspect_ratio' => round($aspect_ratio, 2),
'was_resized' => ($width > $max_dimension || $height > $max_dimension) ? 1 : 0,
'processed_at' => date('Y-m-d H:i:s')
];
$this->model->update($upload->id, $update_data, 'user_uploads');
// Clean up temp file
$this->file->delete($temp_path);
$processed_count++;
}
set_flashdata("Processed {$processed_count} images successfully");
redirect('uploads/batch/' . $batch_id);
}Dimension-Based Logic: After loading an image, use get_width() and get_height() to make intelligent decisions about processing. This allows you to apply different strategies based on image characteristics - organizing by orientation, resizing only when necessary, choosing portrait vs. landscape handling, or applying dimension-specific compression levels.