处理PNG图像时,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);