Resizing image without losing quality in php

Updated:

As a continuation of image processing blog in php in this article I discuss about resizing a given image without losing the quality.

Understanding this can offer advantages like using thumbnail for your own blog. It's good to generate a thumbnail so that it's faster to load image in a web-pages. This idea is quiet around for some time and there are already hundreds of articles supporting it.

First load the image using Imagick

$image = new Imagick('cat.png');

After that, get the height and width

$height = $image->getImageHeight();$width  = $image->getImageWidth();

It's important to know the exact width and height of the image, so that when doing a math, you have idea how much to reduce to maintain it's proportion. For example when defining a new width and height:

$w = $height - 300;$h = $width - 300;

Here I subtracted the original width and height by 300, in this way I can maintained it's proportion when resizing the image to small.

Next divide the original width by height

$ratio = $width / $height;

To get the ratio and then use that ratio to determine new target width and height.

if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newwidth = $w;
$newheight = $w/$r;
}

Load image and create new colored image using new width and height.

$src = imagecreatefrompng('cat.png');
$dst = imagecreatetruecolor($newwidth, $newheight);

then resize and save

imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($dst, 'cat.png');

The full source code.

$image  = new Imagick('cat.png');
$height = $image->getImageHeight();
$width = $image->getImageWidth();
$r = $width / $height;

$w = 600 - 300;
$h = 1200 - 300;

if ($w == 0 || $h == 0) {
exit;
}

if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newwidth = $w;
$newheight = $w/$r;
}

$src = imagecreatefrompng('cat.png');
$dst = imagecreatetruecolor($newwidth, $newheight);

imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($dst, 'cat.png');

end.