Scaling images with alpha blending properly with PHP gd

I had some code trying to scale an image in gd using the imagescale function, that looked something like this:

/* makes a copy of the image, instead of modifying in place */
$target = imagescale($image, $width, $height);

However, the images it created were heavily distorted when using bilinear filtering, and didn’t quite look right with neared neighbour either. For example, with bilinear filtering…

The corrupted image on the left from imagescale, and the properly scaled image on the right.

It turns out I should have used the imagecopyresampled function instead with alpha blending options set:

$target = imagecreatetruecolor($width, $height);
imagealphablending($target, false);
imagesavealpha($target, true);
imagecopyresampled($target, $image, 0, 0, 0, 0, $width, $height, $old_width, $old_height);

Leave a Reply

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