Alex Turpin
Alex Turpin

Reputation: 47776

Why does this transparent PNG cause borders when combined using GD?

I am trying to create an image from an another image using PHP. Here is my code:

<?php
    $width = 109;
    $height = 109;
    $image = imagecreatetruecolor($width, $height);
    $source_under = imagecreatefrompng('ecloid_under.png');
    $black = imagecolorallocate($image, 0x00, 0x00, 0x00);

    imagecolortransparent($image, $black);

    imagecopy($image, $source_under, 0, 0, 0, 0, $width, $height);

    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);
?>

So I am loading this image in $source_under

enter image description here

and copying it over a transparent blank "canvas" image. Here is the result of that operation:

enter image description here

As can be seen, there is a sort of black border around the whole initial image. I think this is due to the fact that initially, the "canvas" image is all black. So there is something wrong with the transparency and the anti-aliasing of the image.

This isn't the first time I have a similar problem, but last time the source image was the cause. This time around, opening it in Photoshop does not show any potential problems with it.

Does anyone know how to fix this?

Upvotes: 6

Views: 5031

Answers (2)

chaos
chaos

Reputation: 124365

You have partial transparency around the edges of your source image. That makes it combine with the black of the canvas image (which you normally can't see because it's 100% transparent), giving the results you see. You could avoid this by making sure your entire alpha channel on the source image is either 100% or 0%, or by choosing a more appropriate base color for your canvas image (i.e. one that matches the background color scheme of your site).

Fabio Anselmo's comment would help in that GIFs don't have a real alpha channel -- GIF transparency is all-or-nothing -- so saving as one will accomplish the 100%-or-0% solution. Unless you're extremely careful it will also give you a "border" right there in the source image -- made up of whatever background color you have or select in the GIF conversion -- as a result of your image's antialiasing. (However, the interlacing part is irrelevant.)

Upvotes: 3

huysentruitw
huysentruitw

Reputation: 28151

Can you try to enable alpha blending on $image before you copy the original to it:

imagealphablending($image, true); 

Second try would be to create a transparent color and to fill $image with that color before the copy.

$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparent);
imagealphablending($image, true); 

Upvotes: 10

Related Questions