簡體   English   中英

處理PNG圖像時,背景為黑色,而不是透明

[英]Black background instead of transparent on PNG images when processing them

我有一個腳本來檢測天氣,它是png圖像或jpeg,還“刪除”圖像周圍的空白。

但是我在所有.png圖像上都得到了黑色背景。 這是為什么?

//load the image

$logo = $json['Logotype'];

$image_type = getimagesize($logo);

if($image_type['mime']=='image/jpeg') {

$img_type = 'jpeg';
$img = imagecreatefromjpeg($logo);

} elseif($image_type['mime']=='image/png') {

$img_type = 'png';
$img = imagecreatefrompng($logo);

}
//find the size of the borders
$b_top = 0;
$b_btm = 0;
$b_lft = 0;
$b_rt = 0;

//top
for(; $b_top < imagesy($img); ++$b_top) {
  for($x = 0; $x < imagesx($img); ++$x) {
    if(imagecolorat($img, $x, $b_top) != 0xFFFFFF) {
       break 2; //out of the 'top' loop
    }
  }
}

//bottom
for(; $b_btm < imagesy($img); ++$b_btm) {
  for($x = 0; $x < imagesx($img); ++$x) {
    if(imagecolorat($img, $x, imagesy($img) - $b_btm-1) != 0xFFFFFF) {
       break 2; //out of the 'bottom' loop
    }
  }
}

//left
for(; $b_lft < imagesx($img); ++$b_lft) {
  for($y = 0; $y < imagesy($img); ++$y) {
    if(imagecolorat($img, $b_lft, $y) != 0xFFFFFF) {
       break 2; //out of the 'left' loop
    }
  }
}

//right
for(; $b_rt < imagesx($img); ++$b_rt) {
  for($y = 0; $y < imagesy($img); ++$y) {
    if(imagecolorat($img, imagesx($img) - $b_rt-1, $y) != 0xFFFFFF) {
       break 2; //out of the 'right' loop
    }
  }
}

//copy the contents, excluding the border
$newimg = imagecreatetruecolor(
    imagesx($img)-($b_lft+$b_rt), imagesy($img)-($b_top+$b_btm));


switch ($img_type)
{
    case "png":
        // integer representation of the color black (rgb: 0,0,0)
        $background = imagecolorallocate($newimg, 0, 0, 0);
        // removing the black from the placeholder
        imagecolortransparent($newimg, $background);

        // turning off alpha blending (to ensure alpha channel information 
        // is preserved, rather than removed (blending with the rest of the 
        // image in the form of black))
        imagealphablending($newimg, false);

        // turning on alpha channel information saving (to ensure the full range 
        // of transparency is preserved)
        imagesavealpha($newimg, true);

        break;
    case "gif":
        // integer representation of the color black (rgb: 0,0,0)
        $background = imagecolorallocate($newimg, 0, 0, 0);
        // removing the black from the placeholder
        imagecolortransparent($newimg, $background);
}

imagecopy($newimg, $img, 0, 0, $b_lft, $b_top, imagesx($newimg), imagesy($newimg));

//finally, output the image
header("Content-Type: image/" . $img_type . "");
imagejpeg($newimg);

這個$background = imagecolorallocate($newimg, 0, 0, 0); 用於黑色背景

使用$background = imagecolorallocatealpha($newimg, 255, 255, 255); 代替

暫無
暫無

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

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