How to destroy an image in PHP using imagedestroy() function?

The imagedestroy() function is an inbuilt PHP function used to destroy an image resource and free any memory associated with it. This function is essential for preventing memory leaks when working with image processing in PHP.

Syntax

bool imagedestroy(resource $image)

Parameters

$image − An image resource created by one of the image creation functions like imagecreatetruecolor() or imagecreatefrompng().

Return Value

Returns true on success or false on failure.

Example 1 − Creating and Destroying a Simple Image

Here's a basic example of creating an image and then destroying it ?

<?php
    // Create a 100x100 image
    $img = imagecreatetruecolor(100, 100);
    
    // Fill with blue color
    $blue = imagecolorallocate($img, 0, 0, 255);
    imagefill($img, 0, 0, $blue);
    
    // Output the image (optional)
    header('Content-Type: image/png');
    imagepng($img);
    
    // Destroy the image to free memory
    $result = imagedestroy($img);
    
    if ($result) {
        echo "Image destroyed successfully";
    }
?>

Example 2 − Multiple Images with Proper Memory Management

When working with multiple images, destroying each one prevents memory buildup ?

<?php
    // Create multiple images
    $img1 = imagecreatetruecolor(50, 50);
    $img2 = imagecreatetruecolor(75, 75);
    $img3 = imagecreatetruecolor(100, 100);
    
    // Process images (add colors, effects, etc.)
    $red = imagecolorallocate($img1, 255, 0, 0);
    imagefill($img1, 0, 0, $red);
    
    // Always destroy images when done
    imagedestroy($img1);
    imagedestroy($img2);
    imagedestroy($img3);
    
    echo "All images destroyed and memory freed";
?>

Key Points

Aspect Description
Memory Management Prevents memory leaks in image processing
When to Use After finishing all operations on an image
Resource Status Image resource becomes invalid after destruction

Conclusion

The imagedestroy() function is crucial for proper memory management in PHP image processing. Always call it after completing image operations to prevent memory leaks and ensure optimal performance.

Updated on: 2026-03-15T09:45:00+05:30

743 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements