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


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

Syntax

bool imagedestroy(resource $image)

Parameters

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.

<?php
   // 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
   imagepng($cropped);

   // It will destroy the cropped image to free/deallocate the memory.
   imagedestroy($cropped);
?>

Output

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

<?php
   // create a 50 x 50 image
   $img = imagecreatetruecolor(50, 50);
   
   // frees image from memory
   imagedestroy($img);
?>

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

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements