处理PNG图像时,黑色背景而不是透明

时间:2013-09-13 01:08:12

标签: php

我有一个脚本可以检测天气,它是一个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);

1 个答案:

答案 0 :(得分:0)

$background = imagecolorallocate($newimg, 0, 0, 0);适用于黑色背景

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

相关问题