我正在使用允许用户上传图片的脚本。脚本调整大小并将图像转换为JPEG。如何在用透明背景调整/转换PNG图像为JPEG格式时用白色替换黑色背景。
我遇到的问题是上传带有透明度的PNG时,得到的JPEG图像在黑色透明处出现。
如何编辑下面的脚本来替换黑色与白色?它已经为GIF做了这个,但不是PNG的。
// RESIZE IMAGE AND PUT IN USER DIRECTORY
switch($this->file_ext)
{
case "gif":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefromgif($this->file_tempname);
$kek=imagecolorallocate($file, 255, 255, 255);
imagefill($file,0,0,$kek);
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "bmp":
$file = imagecreatetruecolor($width, $height);
$new = $this->imagecreatefrombmp($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "jpeg":
case "jpg":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefromjpeg($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
}
chmod($photo_dest, 0777);
return true;
}
我试图编辑的情况下“PNG”:部分以匹配的情况下“GIF”的:代码,但所得到的JPEG完全是白色。
UPDATE:
我固定它自己。
谢谢大家,为了贡献!
我代替:
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
有:
case "png":
$file = imagecreatetruecolor($width, $height);
$new = imagecreatefrompng($this->file_tempname);
$kek=imagecolorallocate($file, 255, 255, 255);
imagefill($file,0,0,$kek);
imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
imagejpeg($file, $photo_dest, 100);
ImageDestroy($new);
ImageDestroy($file);
break;
这imagecolorallocate做什么?它为png接收4个参数,不应该为alpha通道接收5个参数吗? – Andre 2011-04-16 19:27:45
我没有写代码,我是小白。我不知道你的问题的答案。抱歉,我无法帮助你帮助我。 – Jeff 2011-04-16 19:43:15
实际上这些都在手册中。 _imagecolorallocate - 返回表示由给定的RGB分量组成的颜色的颜色标识符._对于alpha透明度,您需要使用'imagecolorallocatealpha',它确实会添加第5个参数:http://php.net/manual/en/ function.imagecolorallocatealpha.php – kasimir 2012-12-06 09:57:07