Resize images with PHP

PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.

In ImageMagick, image resizing is accomplished like this:

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

With GD, you can do it like this:

<?php
// The file
$filename="test.jpg";
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

Leave a Comment