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

PHPServer Side ProgrammingProgramming

imagedestroy() is an inbuilt PHP function that is used to destroy an image and free any memory associated with the image.


bool imagedestroy(resource $image)


imagedestroy() takes only one parameter, $image. It holds the name of an image.

Return Values

imagedestroy() returns true on success and failure on false.

Example 1 − Destroying an image after loading it.

   // Load the png image from the local drive folder
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img32.png');

   // Crop the image
   $cropped = imagecropauto($img, IMG_CROP_BLACK);

   // Convert it to a png file

   // It will destroy the cropped image to free/deallocate the memory.


Note − By using imagedestroy() function, we have destroyed the $cropped variable and therefore, it can no longer be accessed.

Explanation − In Example1, imagecreatefrompng() loads an image from the local drive folder and crops a part of the image from the given image using imagecropauto() function. After cropping, imagedestroy() function is used to destroy the image. We cannot access the image or the $cropped variable after destroying the image.

Example 2

   // create a 50 x 50 image
   $img = imagecreatetruecolor(50, 50);
   // frees image from memory

Note − In the above PHP code, a 50×50 image is created using the imagecreatetruecolor() function. After creating the image, imagedestroy() function is used to free or deallocate the used memory.

Updated on 09-Aug-2021 10:05:23