开发者

Image transparency in PHP GD library

开发者 https://www.devze.com 2023-04-04 16:40 出处:网络
I need to create a PNG image from 4 parts of another PNG image with different levels of transparency using GD library in PHP. For example:

I need to create a PNG image from 4 parts of another PNG image with different levels of transparency using GD library in PHP. For example:

Result should look like this

I tried to do this thing in different ways but I coudn't achieve the desired re开发者_如何转开发sult.

Thank you in advance ;)


Load your image with imagecreatefrompng(). Create a truecolor image with imagecreatetruecolor() and then set it fully transparent with imagecolorallocatealpha() and imagefill(). Then set alpha blending mode for both the source and destination images with imagealphablending(). After this you can use imagecopymerge() to copy the image with alpha.

Unfortunately it's not possible to enforce an alpha multiplier for imagecopymerge(), so this will get you only halfway there -- Inconvenient options include repeating imagecopymerge() calls on those parts of the image you want to be less transparent, choosing between several source images depending on the level of transparency you want to use, or going through the image pixel-by-pixel, which is inconveniently slow.

If you are not married to the image* functions, consider using ImageMagick instead. It is much more robust.


I did this:

$output = imagecreatetruecolor([width], [height]);
imagesavealpha($output , true);

$trans_colour = imagecolorallocatealpha($output , 0, 0, 0, 127);
imagefill($output , 0, 0, $trans_colour);

Now the image is transparent :)

The whole script:

$output = imagecreatetruecolor([width], [height]);
imagesavealpha($output , true);

$trans_colour = imagecolorallocatealpha($output , 0, 0, 0, 127);
imagefill($output , 0, 0, $trans_colour);

header('Content-Type: image/png');

imagepng($output);

imagedestroy($output);

Hope it helps!


This worked for me with both gif and png (of course, change every reference of png in this example to gif if using that image type).

$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
$colour = imagecolorallocate($virtual_image,255,255,255);
imagefill($virtual_image , 0, 0, $colour);
imagealphablending($virtual_image,true);
imagesavealpha($virtual_image , true);

//the next line only if you're resizing to a new $width/$height, otherwise leave this line out
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

header('Content-Type: image/png');

if (imagepng($virtual_image)) imagedestroy($virtual_image);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号