PHP调整PNG图像大小生成黑色背景


PHP resizing PNG images generate black background

这是我用来显示或调整大小并显示缓存标头的代码的一部分。它适用于JPG图像。但是PNG图像会添加黑色背景。这类问题可以在SO和Google上找到,但几乎被接受或建议的答案都是一样的:imagealphablending - FALSE和imagesavealpha - TRUE。但在我的情况下,什么都不起作用。问题是什么?

$image_information=getimagesize($img);
if($image_information['mime']=='image/gif')
{
    $img=imagecreatefromgif($img);
    $type="gif";
    $image_header="image/gif";
}
elseif($image_information['mime']=='image/png')
{
    $img=imagecreatefrompng($img);
    $type="png";
    $image_header="image/png";
}
else
{
    $img=imagecreatefromjpeg($img);
    $type="jpg";
    $image_header="image/jpeg";
}
$width=imagesx($img);
$height=imagesy($img);
if((isset($w))&(!isset($h))) // If Width or Height is posted, calculate the aspect dimensions
{
    $h=($height/$width*$w);
}
if((isset($h))&(!isset($w)))
{
    $w=(($h*$width)/$height);
}
if(!isset($w))
{
    $w=$width;
}
if(!isset($h))
{
    $h=$height;
}

$new_image=imagecreatetruecolor($w, $h);
if($type=="gif")
{
    $background=imagecolorallocate($new_image, 0, 0, 0);
    // removing the black from the placeholder
    imagecolortransparent($new_image, $background); 
}
elseif($type=="png")
{
    imagealphablending($new_image, FALSE);
        imagesavealpha($new_image, TRUE);
    $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        imagefilledrectangle($new_image, 0, 0, $w, $h, $transparent);
}
imagecopyresampled($new_image,$img,0,0,0,0,$w,$h,$width,$height);
$seconds_to_cache = 864000; // Add cache headers
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control:max-age=$seconds_to_cache, must-revalidate");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");

header('Content-Type: $image_header');
if($type="jpg")
imagejpeg($new_image, NULL, 75);
elseif($type=="png")
imagepng($new_image, NULL, 75);
elseif($type=="gif")
imagegif($new_image, NULL);
imagedestroy($new_image);

编辑:我保存了图像到我的系统,尝试打开,

  1. Picasa照片查看器-图像打开黑色BG。
  2. Ms Paint - Image以黑色BG打开。
  3. Photoshop CS6 -错误信息弹出:无法打开,因为程序错误。

您没有保存原始图像中的alpha通道。

添加

imagealphablending($img, true);

右边的代码

$width=imagesx($img); $height=imagesy($img);

编辑:

,然后试试这个

$transparent = imagecolortransparent($new_image, imagecolorallocatealpha($new_image, 255, 255, 255, 127));
imagefill($new_image, 0, 0, $transparent);

用填充矩形代替透明代码

我建议您使用一个编码良好的类来进行图像处理。Verot.net的用于图片上传的php类,除了上传操作之外,还提供了一个DRY、结构良好的API中的各种图片操作功能。最后,您的代码将更加可移植和面向未来。