簡體   English   中英

重新創建的png圖像是黑色的

[英]Recreated png image is black

示例圖片

注意:SO已將上述參考圖像轉換為jpeg。 這是透明的PNG


以下是一個示例代碼,它在新畫布上重新創建png圖像並保留透明度。 如您所見,它還允許像素級操作,例如。 使用自定義函數,如custom_func($r, $g, $b) ,這在本問題的底部更好地說明。

基本上,這段代碼成功地在新畫布上 重新創建/重繪上面的圖像。 請注意,上圖中天空完全透明

    $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而異?

理想情況下,我希望我的代碼能夠保留源png圖像的透明度狀態(透明,半透明或不透明),並將其轉換為重新創建的圖像。 正如你所看到的,除了上面的情況,我已經能夠實現它。


以防萬一,這是我的環境。 Windows 7 - 64位** Wampserver2.5 ** Apache-2.4.9 ** Mysql-5.6.17 ** php5.5.12-64b。 這里還有一個帶有getimagesize()的圖像的var_dump:

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));進行略微修改來實現的imagesetpixel($new_image, $x, $y, imagecolorallocatealpha($image, 100, $g, $b, $alpha));

操縱透明圖像

您的第二個圖像是8位,這意味着它最多只支持256種顏色。 這使它成為“基於調色板”的圖像,因此它不支持Alpha透明度。

只需在創建$image后添加以下行,即可解決問題:

imagepalettetotruecolor($image);

這對已經是真彩色的圖像沒有任何影響,因此grass.png繼續正確處理grass.png PHP手冊頁

如果轉換完成,或者源圖像已經是真彩色圖像,則返回TRUE,否則返回FALSE。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM