destroy()

public function destroy(): void

Description

Frees memory allocated to the loaded image resource. This method releases the GD image resource from memory and should be called when image processing is complete, especially when processing multiple or large images in a single request.

Memory Management: Failure to call destroy() in scripts that process multiple images can lead to memory exhaustion. PHP's garbage collector may not release image resources immediately, causing memory usage to accumulate throughout the request lifecycle.

Parameters

This method takes no parameters.

Return Value

Type Description
void This method does not return a value. It releases the image resource from memory.

Example #1

The code sample below demonstrates the most basic use of destroy().

PHP
// Load and process an image
$this->image->load('modules/gallery/photos/photo.jpg');
$this->image->resize_to_width(800);
$this->image->save('modules/gallery/photos/photo_resized.jpg');

// Free memory when done
$this->image->destroy();

When to Use destroy(): Call destroy() after you've finished all operations on an image and have either saved it or output it to the browser. Once destroyed, you'll need to load a new image before performing additional operations.

Example #2

The example above shows how to process multiple images efficiently by destroying each after processing.

PHP
public function batch_resize_products(): void {
    // Get all products with images
    $products = $this->model->get_many_where('image_filename IS NOT NULL', 'products');
    
    if ($products === false) {
        redirect('products/manage');
    }
    
    $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);
            
            // Resize to standard dimensions
            $this->image->resize_to_width(600);
            
            // Save the resized version
            $output_path = 'modules/products/images/resized_' . $product->image_filename;
            $this->image->save($output_path, 85);
            
            // Critical: Free memory before processing next image
            $this->image->destroy();
            
            $processed++;
        }
    }
    
    set_flashdata("Processed {$processed} product images");
    redirect('products/manage');
}

The Batch Processing Pattern: When processing multiple images in a loop, always call destroy() at the end of each iteration. This prevents memory from accumulating as each image is processed. Without this, processing 50 high-resolution images could easily exceed PHP's memory limit.

Example #3

The example above demonstrates managing memory when creating multiple size variations from a single source image.

PHP
public function generate_image_sizes(): 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 size variations
    $sizes = [
        'large' => 1200,
        'medium' => 800,
        'small' => 400,
        'thumbnail' => 150
    ];
    
    foreach ($sizes as $size_name => $width) {
        // Load source image fresh for each size
        $this->image->load($source_path);
        
        // Resize to target width
        $this->image->resize_to_width($width);
        
        // Save the variation
        $output_dir = 'modules/gallery/' . $size_name;
        if (!$this->file->exists($output_dir)) {
            $this->file->create_directory($output_dir, 0755);
        }
        
        $output_path = $output_dir . '/' . $photo->filename;
        $this->image->save($output_path, 85);
        
        // Free memory before loading next variation
        $this->image->destroy();
    }
    
    set_flashdata('All image sizes generated successfully');
    redirect('gallery/view/' . $photo_id);
}

Example #4

The example above shows proper memory management in a method that processes user uploads and generates thumbnails.

PHP
public function process_gallery_upload(): void {
    $gallery_id = segment(3, 'int');
    
    // Validate upload
    $this->validation->set_rules('userfile', 'Gallery Image', 'required|allowed_types[jpg,png,gif]|max_size[10000]');
    
    if ($this->validation->run() === true) {
        // Configure upload
        $config = [
            'destination' => 'galleries/uploads',
            'upload_to_module' => true,
            'make_rand_name' => true
        ];
        
        // Ensure directories exist
        $upload_dir = 'modules/gallery/galleries/uploads';
        $thumb_dir = 'modules/gallery/galleries/thumbs';
        
        if (!$this->file->exists($upload_dir)) {
            $this->file->create_directory($upload_dir, 0755);
        }
        
        if (!$this->file->exists($thumb_dir)) {
            $this->file->create_directory($thumb_dir, 0755);
        }
        
        // Upload the image
        $file_info = $this->image->upload($config);
        
        // Load uploaded image for thumbnail generation
        $this->image->load($file_info['file_path']);
        
        // Create square thumbnail
        $this->image->resize_to_width(200);
        $this->image->crop(200, 200, 'center');
        
        // Save thumbnail
        $thumb_path = $thumb_dir . '/' . $file_info['file_name'];
        $this->image->save($thumb_path, 85);
        
        // Free memory now that processing is complete
        $this->image->destroy();
        
        // Store in database
        $data = [
            'gallery_id' => $gallery_id,
            'filename' => $file_info['file_name'],
            'file_path' => $file_info['file_path'],
            'thumbnail_path' => $thumb_path,
            'file_size' => $file_info['file_size'],
            'uploaded_at' => date('Y-m-d H:i:s')
        ];
        $this->model->insert($data, 'gallery_images');
        
        set_flashdata('Image uploaded and processed successfully');
        redirect('gallery/view/' . $gallery_id);
    } else {
        $this->upload_form($gallery_id);
    }
}

Automatic Cleanup: PHP will automatically release image resources at the end of script execution, so destroy() is not strictly required for single-image operations. However, it's good practice to explicitly free resources when done, especially in long-running scripts or when processing multiple images.