PHP / GD ImageSaveAlpha和ImageAlphaBlending [英] PHP/GD ImageSaveAlpha and ImageAlphaBlending

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

问题描述

我正在使用GD调整大小和转换图像,但是在我的测试中,我发现将透明PNG转换为JPEG时有一种奇怪的行为。根据手册 ImageAlphaBlending ()默认打开,但为了保持透明度,我必须设置 ImageSaveAlpha ()为true(这又要求我将ImageAlphaBlending()设置为false)。所以正确的方法应该是:

I'm using GD to resize and convert images, however during my tests I found a weird behavior when converting transparent PNG's to JPEG's. According to the manual ImageAlphaBlending() is on by default but in order to preserve the transparency I must set ImageSaveAlpha() to true (which in turn requires that I set ImageAlphaBlending() to false). So the correct way should be:

$result = ImageCreateFromPNG(...);
ImageAlphaBlending($result, false);
ImageSaveAlpha($result, true);
ImageFill($result, 0, 0, IMG_COLOR_TRANSPARENT);
ImageJPEG($result);
ImageDestroy($result);

然而,如果我以正确方式执行此操作,则JPEG中的所有透明区域都会显示为黑色。这似乎在我的测试中起作用(透明区域上带有白色背景的JPEG):

However if I do it the "correct" way all the transparency area comes up black in the JPEG. This seems to work (JPEG with white background on transparent areas) on my tests:

$result = ImageCreateFromPNG(...);
ImageAlphaBlending($result, true); // true by default, but still...
ImageSaveAlpha($result, true);
ImageFill($result, 0, 0, IMG_COLOR_TRANSPARENT);
ImageJPEG($result);
ImageDestroy($result);

有人可以请教我这个问题吗?

Can someone please enlighten me on this subject?

推荐答案

这可能取决于您的PNG。 PNG文件可以包含背景颜色,可以在透明度不起作用时使用。你的PNG可能有白色背景。当您将imageaplhablending设置为true时,它会从PNG中获取背景颜色,并在编写JPEG时使用它。当你将它设置为false时,它会选择GD的默认值为黑色。

It probably depends on your PNG. A PNG file can contain a background color, which can be used when transparency doesn't work. Your PNG probably has a white background. When you set imageaplhablending to true it picks up the background color from your PNG and uses that when writing the JPEG. When you set it to false it picks the default for GD which is black.

你可以自己试试。创建透明PNG并使用橙色或粉红色背景颜色保存。你的第二个例子应该显示颜色。

You can try it for yourself. Create a transparent PNG and save it with an orange or pink background color. Your second example should show that color.

顺便说一下,PNG背景颜色技巧对于IE6图像来说是一个不错的选择。 IE6不支持透明PNG,因此它会以您保存的任何背景颜色显示它们。保存透明PNG时,请使用与网站相同的背景颜色保存它们。它看起来比IE6中的PNG图像周围的白色或黑色框更好。

By the way, the PNG background color trick is a nice one for IE6 images. IE6 does not support transparent PNGs so it will display them with whatever background color you saved them with. When saving transparent PNGs, save them with the same background color as your website. It will look better than white or black boxes around your PNG images in IE6.

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

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