How to resize an image in PHP

How to resize an image in PHP

This post has been viewed 246 times.

In this tutorial, we will learn to resize an image in PHP.

Whenever you are doing something like a CMS for your website that requires an image to be uploaded then you can have a problem where users upload images in different dimensions.

This can be a problem in the front-end as your design will not be the same for all.

This is why we need to learn to resize an image in PHP. As long as the file is on the server then you can use this method to resize your images.

This can also be used to resize an image on upload meaning after uploading the original image it will automatically be resized after uploading.

What you’ll need:

  • An image (must be .jpg,.jpeg,.gif, and .png only).
  • A text editor.
  • A local/live server.

Step 1: Get a copy of this PHP function.


The PHP function accepts three (3) parameters. The first parameter is a string which has the filename of the image that is going to be resized. The second parameter is an integer, this will be the new width of your image. The third and last parameter is also an integer, this will be the new height of your image.

Step 2: Use the PHP function.

Our sample image laptop.jpg having a dimension of 1920x1280.

Picture 2.1. Our sample image laptop.jpg having a dimension of 1920×1280.

In this example, we are going to have an image laptop.jpg which has a dimension of 1920×1280 and we will want to downscale this image to the quarter of its original size (480×320).

Now, the second file that we are going to have is resize.php that contain the function above and this file will also make the resizing possible.

Since the filename of our sample image is laptop.jpg and it is also in the same directory then we can use the function as follows.

After executing the file resize.php we can see now that our image has lesser file size and has a lower dimension.

Our sample image laptop.jpg having a new dimension of 480x320.

Picture 2.2. Our sample image laptop.jpg having a new dimension of 480×320.

That’s it, we have now successfully resized an image in PHP.

You may notice that whenever you use PHP file upload, the file will be uploaded to the server. After a successful upload, just call the function after the file has been uploaded for it to be resized.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.