How To Resize Images in PHP using GD Library

A quick tutorial on resizing images using the GD library in PHP.

2 min read โ€ข
121 1 0

Learn how to resize JPEG and PNG images using PHP's built-in GD library.

๐Ÿ–ผ๏ธ Why Resize Images in PHP?

Resizing images on the server helps reduce load times, save bandwidth, and create uniform media assets. The GD library is built into PHP and provides an efficient way to handle image manipulation without external tools.

๐Ÿ” Check if GD Library is Installed

<?php if (extension_loaded('gd')) { echo 'GD library is available!'; } else { echo 'GD library is not installed.'; } ?>

If not installed, you may need to run something like sudo apt install php-gd (Linux) or enable it in your php.ini on Windows.

โš™๏ธ Resize an Image

This example resizes a JPEG image to a max width of 300px, preserving the aspect ratio:

<?php $sourcePath = 'original.jpg'; $destPath = 'resized.jpg'; list($width, $height) = getimagesize($sourcePath); $newWidth = 300; $newHeight = floor($height * ($newWidth / $width)); $src = imagecreatefromjpeg($sourcePath); $tmp = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imagejpeg($tmp, $destPath, 90); imagedestroy($src); imagedestroy($tmp); echo "Image resized successfully."; ?>

๐Ÿ“ Resizing PNG Images

Use imagecreatefrompng() and imagepng() for PNG support:

$src = imagecreatefrompng('original.png'); $tmp = imagecreatetruecolor($newWidth, $newHeight); imagealphablending($tmp, false); imagesavealpha($tmp, true); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imagepng($tmp, 'resized.png');

๐Ÿ’ก Tips and Considerations

  • Use imagesx() and imagesy() if you already have a resource
  • Always validate file types before processing
  • Use imagejpeg() quality param to control output size (0โ€“100)
  • For user uploads, restrict max dimensions and file size

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel