Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP GD resizing transparent image giving black border

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 before

After enter image description here

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.

like image 827
Alex Turpin Avatar asked Nov 15 '11 18:11

Alex Turpin


1 Answers

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:

Image as seen 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.

like image 158
Brad Avatar answered Sep 20 '22 03:09

Brad