Saturday, September 6, 2025
HomeLanguagesPHP | imagedestroy() Function

PHP | imagedestroy() Function

The imagedestroy() function is an inbuilt function in PHP which is used to destroy an image and frees any memory associated with the image.

Syntax:

bool imagedestroy( resource $image )

Parameters: This function accepts a single parameter $image which holds the name of image.

Return Value: This function returns TRUE on success and FALSE on failure.

Below examples illustrate the imagedestroy() function in PHP:

Example 1: Destroying image after using it.




<?php
  
// Load the png image
$im = imagecreatefrompng(
   
// Crop the image
$cropped = imagecropauto($im, IMG_CROP_BLACK);
  
// Convert it to a png file
header('Content-type: image/png');  
imagepng($cropped);
  
// Destroy the cropped image to deallocate the memory
imagedestroy($cropped);
?>


Output:

$cropped variable is destroy by the end line
and you can't access it after that line.

Example 2: Checking if the variable is destroyed.




<?php
  
// Load the png image
$im = imagecreatefrompng(
  
header('Content-type: image/png');
  
// Destroy the image to deallocate the memory
imagedestroy($im);
  
// Try to access the destroyed variable
imagepng($im);
?>


Output:

PHP log will give a error as the variable is destroyed. PHP Warning:  imagepng(): supplied resource is not a valid Image resource.

Reference: https://www.php.net/manual/en/function.imagedestroy.php

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS