Resize an image using the GD library in PHP

Today we will explain to you how to resize an image using the GD library in PHP. When we are working with the gallery or individual images to display on a page then it’s more important to reduce the size of an image. That way we can improve the page speed and user experience and for that, we will use the GD library.

We’ll take an example to upload an image and parallelly create a thumbnail of the same image using the GD library in PHP to store in a different folder.

Steps to resize an image using the GD library

  1. Enable GD extension
  2. Create HTML form
  3. Write PHP code to resize an image
  4. Output

1. Enable GD extension

First, we have to enable the GD Support before we start. You can easily check on your server just create a simple php file and write phpinfo() then access it on a web browser.

Create a PHP file and run it in the browser.

check-gd-support.php

Now search “GD Support” in “gd” section and it should be “Enabled“. Check the below image for your reference.

GD Supports - Clue Mediator
GD Supports – Clue Mediator

If GD Library is not installed on your server then you can manually install GD library and enable it.

2. Create HTML form

In the next step, we will create a HTML form to manage the upload image UI.

index.php

Let’s create a uploads folder in root directory and also create a thumbs folder inside the “uploads” folder.

3. Write PHP code to resize an image

Now, we create a file named upload.php and write the following php code to resize the image. Using this code we will create thumbnail images of jpg, jpeg, png, gif.

upload.php

Here, we compare image type with IMAGETYPE_JPEG, IMAGETYPE_PNG and IMAGETYPE_GIF that are the predefined constants in php and you can check it using the below code.

4. Output

Run the above code and check the output.

Output - Resize an image using the GD library in PHP - Clue Mediator
Output – Resize an image using the GD library in PHP – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. Tanja says:

    Pretty! This was an incredibly wonderful post. Thank you
    for supplying these details.

Leave a Reply

Your email address will not be published. Required fields are marked *