I am trying to downsize some transparents images in PHP with GD, and whenever I do, there is a weird black-ish border that is added around it.
Before
After
Code
<?php
$image = imagecreatefromstring(file_get_contents('logo.png'));
$width = imagesx($image);
$height = imagesy($image);
$newWidth = $width - 1;
$newHeight = $height - 1;
$output = imagecreatetruecolor($newWidth, $newHeight);
imagecolortransparent($output, imagecolorallocatealpha($output, 0, 0, 0, 127));
imagealphablending($output, false);
imagesavealpha($output, true);
imagecopyresampled($output, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
header('Content-Type: image/png');
imagepng($output);
?>
It seems that if I change the code for the new dimensions to be the same as the old (removing the - 1
), no black borders appear. So the resize is causing the problem.
Does anyone have an idea what might be wrong?
Edit: I just realized it only happens with imagecopyresampled
and not imagecopyresized
. However, imagecopyresampled
gives a far better visual effect and I'd like to make it work if possible.
I think the problem here is your source image.
What you have is not a true-color PNG with alpha channel, but an indexed-color PNG with a transparent color. This is apparent if you open the image in Photoshop:
This image was created with anti-aliasing already (which gives the yellow text that white-ish border seen here), but when you re-size it, the sub-pixel calculations may go outside of their borders a bit.
I suspect if you fix the image, making it full RGB with an alpha channel, you won't have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With