重新创建的 png 图像是黑色的

Recreated png image is black

注意:SO 已将上述参考图像转换为 jpeg。这是 transparent PNG.


以下示例代码在新 canvas 上重新创建 png 图像 并保留透明度。如您所见,它还允许像素级操作,例如。使用像 custom_func($r, $g, $b) 这样的自定义函数,在这个问题的底部有更好的说明。

基本上这段代码recreates/redraws上图在新的canvas上成功原样。 请注意,上图中的天空是完全透明的

    $image = imagecreatefrompng('grass.png');

    $x_dimension = imagesx($image);
    $y_dimension = imagesy($image);
    $new_image = imagecreatetruecolor($x_dimension, $y_dimension);

    // create a transparent canvas
   $trans_color = imagecolorallocatealpha($new_image, 0x00, 0x00, 0x00, 127);
   imagefill($new_image, 0, 0, $trans_color);

     for ($x = 0; $x < $x_dimension; $x++) {
          for ($y = 0; $y < $y_dimension; $y++) {
          $rgb = imagecolorat($image, $x, $y);
          $r = ($rgb >> 16) & 0xFF;
          $g = ($rgb >> 8) & 0xFF;
          $b = $rgb & 0xFF;
          $alpha = ($rgb & 0x7F000000) >> 24;
          //$pixel = custom_function($r, $g, $b);
          imagesetpixel($new_image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
      }
      }
     imagesavealpha($new_image, true);
     imagepng($new_image, 'grass-result.png');

然而,当我 运行 在下面这个特定的 png 图像上使用相同的代码时。

它给了我这样一个几乎是黑色的图像。


我想了解这里发生了什么以及为什么?最重要的是,我想知道可能影响该过程的可能因素,以便我对其进行调查。为什么结果从一个 png 到另一个不同?

理想情况下,我希望我的代码能够保留源 png 图像的透明度状态(透明、半透明或不透明)并将其原样传输到重新创建的图像。如您所见,我已经能够实现它,除了上面的情况。


以防万一,这是我的环境。 Windows 7 - 64 位 ** Wampserver2.5 ** Apache-2.4.9 ** Mysql-5.6.17 ** php5.5.12-64b。这里还有一张 var_dump 的图像 getimagesize() :

array (size=6)
  0 => int 228
  1 => int 230
  2 => int 3
  3 => string 'width="228" height="230"' (length=24)
  'bits' => int 8
  'mime' => string 'image/png' (length=9)

更新 这里证明示例图像确实是透明的,并且可以在保持透明度的同时对其进行操作。请注意,图像的底部现在更呈褐色。这是通过对这一行 imagesetpixel($new_image, $x, $y, imagecolorallocatealpha($image, 100, $g, $b, $alpha));

稍作修改来实现的

您的第二张图片是 8 位的,这意味着它最多只支持 256 种颜色。这使它成为 'palette-based' 图像,因此它不支持 alpha 透明度。

只需在创建 $image 后添加以下行即可解决问题:

imagepalettetotruecolor($image);

这对已经是真彩色的图像没有任何影响,因此 grass.png 继续正确处理。来自 PHP manual page:

Returns TRUE if the conversion was complete, or if the source image already is a true color image, otherwise FALSE is returned.