繁体   English   中英

PHP GD imagecreatefromstring 丢弃透明度

[英]PHP GD imagecreatefromstring discards transparency

我一直在尝试使我的应用程序具有透明度(它在存储图像之前动态调整图像大小),并且我认为在对imagealphablendingimagesavealpha进行了很多误导之后,我终于缩小了问题的imagesavealpha 源图像永远不会以适当的透明度加载!

// With this line, the output image has no transparency (where it should be
// transparent, colors bleed out randomly or it's completely black, depending
// on the image)
$img = imagecreatefromstring($fileData);
// With this line, it works as expected.
$img = imagecreatefrompng($fileName);

// Blah blah blah, lots of image resize code into $img2 goes here; I finally
// tried just outputting $img instead.

header('Content-Type: image/png');
imagealphablending($img, FALSE);
imagesavealpha($img, TRUE);
imagepng($img);

imagedestroy($img);

从文件加载图像将是一些严重的架构困难; 此代码与从 iPhone 应用程序查询的 JSON API 一起使用,在这种情况下,将图像作为 base64 编码字符串上传到 POST 数据中更容易(并且更一致)。 我是否绝对需要以某种方式将图像存储为文件(只是为了让 PHP 可以再次将其加载到内存中)? 有没有办法从$fileData创建一个可以传递给imagecreatefrompng

Blech,结果证明这最终是由于一个完全独立的 GD 调用来验证图像上传。 我忘了将imagealphablendingimagesavealpha添加到该代码中,它正在创建一个新图像,然后将其传递给调整大小的代码。 无论如何,这可能应该改变。 非常感谢 Goldenparrot 将字符串转换为文件名的出色方法。

您可以使用此代码:

$new = imagecreatetruecolor($width, $height);

// preserve transparency

imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));

imagealphablending($new, false);

imagesavealpha($new, true);

imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

imagepng($new);

imagedestroy($new);

它将为您制作透明图像。 祝你好运 !

我是否绝对需要以某种方式将图像存储为文件(只是为了让 PHP 可以再次将其加载到内存中)?

不。

文档说:

您可以使用 php v5.2.0 中的data://协议

例子:

// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM