PHP/GD-透明背景 [英] PHP/GD - transparent background

查看:208
本文介绍了PHP/GD-透明背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想结合GD在PHP中执行以下操作.不幸的是,ImageMagick不是一个选项,但这似乎是一个普遍的问题,有必须作为解决方案,我似乎找不到它.

I want to do the following in PHP in combination with GD. ImageMagick is not an option, unfortunately, but this seems like such a common problem that there has to be a solution, I just can't seem to find it.

我想创建一个透明背景的PNG.然后,我想在其上绘制一个矩形,在其上复制图像,并添加一些文本.一种方法如下:

I want to create a PNG with a transparent background. Then I want to draw a rectangle on it, copy an image on it, and add some text. One way of doing this is as follows:

$image = ImageCreateTrueColor (800, 600);
imagecolortransparent ($image, 0); //0 is pure black, the default fill color
imagerectangle (...);
//code to copy an image
imagettftext ($image, ...);
imagepng ($image);

这很好用,除了复制的图像的一部分可能是黑色和/或文本可能是黑色.然后,这也变得透明了,这是我想要的.

This works fine, except that part of the copied image might be black, and/or the text might be black. This then also becomes transparent, which is something I don't want.

imagefill ($image, 0,0, 0x7FFF0000);
imagetransparent ($image, 0x7FFF0000);

上面的代码是我在网上找到的,用红色填充,然后使红色透明.同样,这会使图像中的所有红色变为透明.我可以选择一种不太可能出现的颜色,但是我不能保证.

The above code is something I found online, which fills it with red, then makes red transparent. Again, this causes all red in the image to become transparent. I could choose a color that is unlikely to occur, but I can't guarantee this.

有什么我想念的吗?可以解决这个问题吗? 感谢您的答复!

Is there something I'm missing? Can this be fixed? Thanks for your replies!

推荐答案

imagecolortransparent可能不是您想要的,因为单色透明令人讨厌.

imagecolortransparent is probably not what you want here if you're merging images, as single-colour transparency is nasty.

相反,请尝试使用透明的填充蒙版,如下所示:

Instead, try it with a transparent fill mask like so:

<?php
$image = imagecreatetruecolor(100, 100);

// Transparent Background
imagealphablending($image, false);
$transparency = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparency);
imagesavealpha($image, true);

// Drawing over
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 25, 25, 75, 75, $black);

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

这篇关于PHP/GD-透明背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆