Crop And Resize Animated GIF without Losing The Animation in PHP Website

Crop And Resize Animated GIF without Losing The Animation in PHP Website
5 (100%) 1 vote


Uploading an image on a PHP website isn’t a hard job, but uploading an animated GIF image file without losing the animation is no novice cup of tea. So in today’s PHP tutorial, we’re going to make a demo on how to resize Animated GIF in a PHP website.

In this PHP tutorial, we’re going to add a button to allow user for uploading any size of GIF images in PHP webpage.

Let’s Get Started

First, create a form with input type = “file” and submit button.

<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" value="select..">
<input type="submit" value="Upload" name="upload">

Once you create the form, check folder path whether it exists or not. If it doesn’t exist, then create a path to upload your image.

chmod($uploadPath, 0777);

Next, check the file extension that you’ll allow to upload. Since we’re developing for GIF images, we’ll only allow image (GIF) extension. So if the image is of GIF extension then it will allow to upload, otherwise it will fire an exception.

$types = array('jpeg', 'gif','png');
$filename    = $_FILES["image"]["name"];
$extension   = end(explode(".", $filename));

echo "Sorry your file was not uploaded. It may be the wrong filetype. We only allow JPG, GIF, and PNG filetypes. <br/><br/>";

Now it’s time to upload image and unlink or delete old images. Here we’ll scan the directory and delete old images and upload image using “move_uploaded_file”.

$newfilename = "image.".$extension;
//read images and delete last
$images = glob($dirname."*");
foreach($images as $image) {
//upload new image
chmod($uploadPath.$newfilename, 0777);
echo "Something went wrong please try again. <br/><br/>";

After completing this code, open your browser and go to http://localhost/image-upload (your php file name here)/
Once you open it, it’ll look like specified in the below screenshot. Now you can upload a GIF by clicking on the ‘browse’ button.


After clicking on ‘browse’ button, select any GIF image from your local system.


After selecting a GIF image, you need to click on upload button. It will show your image and give you output shown as below:


That’s it!

We also shared this code on GitHub.

You can directly download the entire source code of resizing animated GIF.

By following the above steps, you can resize any GIF file without losing the animation quality. If you face any problem implementing this feature, contact our PHP developers by filling the form below.

Do you know most big brands like Facebook, Tumblr, and Wiki are built on PHP only? And, building a website in PHP has many benefits like secured, independent, and cost efficient. So, if you want to hire PHP developer for building your website, go ahead. Contact us now.