18
1
0
How To Resize Images in PHP using GD Library

How To Resize Images in PHP using GD Library

Published on July 3, 2025 by OBSCountdown Editorial

Resize Images in PHP using GD Library

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's comment. Cancel
18
1
0
Join Our OBS Community

Loading...

Join Now