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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


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

My Personal Notes arrow_drop_up

I love Open Source Culture have contributed to phpMyAdmin, LibreOffice, Ant-Design and Web is my passion

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.