PNG图像显示上传/调整大小的黑色背景

时间:2017-02-27 08:59:55

标签: php image-resizing

我正在上传图片及其大小调整,但在PNG上,它显示黑色背景。

请您查看代码并告诉我这是什么问题?

$newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        if ($ext == "jpg" || $ext == "jpeg")
        {
            $source = imagecreatefromjpeg($image);
        }
        else
        if ($ext == "png")
        {
            $source = imagecreatefrompng($image);
        }
        else
        {
            $source = imagecreatefromgif($image);
        }

        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
        imagejpeg($newImage,$image,90);
        chmod($image, 0777);
        return $image;

2 个答案:

答案 0 :(得分:1)

答案:

在imagecopyresampled()函数

之前添加了此代码
$tmp = imagecreatetruecolor($new_width,$new_height);
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));

它开始按我的意愿工作....

答案 1 :(得分:0)

我遇到了同样的问题,我使用http://php.net/manual/en/function.imagecolorallocatealpha.php

中的alpha着色添加以下代码
//setting transparent color
  $color = imagecolorallocatealpha($this->imageResized, 0, 0, 0, 127);
//seting the image fill to the transparent color
  imagefill($this->imageResized, 0, 0, $color);
//saving the image with transparency before resizing
  imagesavealpha($this->imageResized, TRUE);