问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/8141131/php-gd-resizing-transparent-image-giving-black-border