【问题标题】:PHP GD imagecreatefromstring discards transparencyPHP GD imagecreatefromstring 丢弃透明度
【发布时间】:2012-08-24 06:40:30
【问题描述】:

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

// 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 一起使用,在这种情况下更容易(并且更一致)将图像作为 POST 数据中的 base64 编码字符串上传。我是否绝对需要以某种方式将图像存储为文件(以便 PHP 可以再次将其加载到内存中)?有没有办法从$fileData 创建一个可以传递给imagecreatefrompng 的流?

【问题讨论】:

  • 无法在PHP 5.3.10 / GD 2.0 上重现该问题,工作正常。你用的是什么版本?可能来自其他东西..损坏的PNG条目?像 iPhone 应用程序上传质量差的图像?只是在黑暗中拍摄
  • 我在我的 Debian 机器上使用 GD 2.0.34(兼容 2.0.34)在 PHP 5.3.16-1~dotdeb.0(使用 Suhosin)上测试了这个,当我运行 imagepng 时,透明部分是黑色的。这发生在我使用 imagecreatefromstringimagecreatefrompng 时。
  • 我使用的是 PHP 5.3.10 / GD(2.0.34 兼容)。
  • 编辑:我没有用 imagealphablendingimagesavealpha 测试这个。
  • 找到了这个,不确定是否有帮助:theolagendijk.com/2009/10/24/…

标签: php php-gd


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用此代码:

    $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);
    

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

    【讨论】:

    • 这为我整理了所有内容。谢谢。
    【解决方案3】:

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

    没有。

    Documentation 说:

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

    例子:

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

    【讨论】:

    • 你应该可以做到$img = imagecreatefrompng('data://image/png;base64,'.$base64Image);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2011-08-20
    • 2010-12-14
    • 2011-01-09
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多