【发布时间】:2011-08-07 00:47:53
【问题描述】:
我正在使用一个允许用户上传图像的脚本。该脚本调整图像大小并将图像转换为 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;
}
我尝试编辑 case "png": 部分以匹配 case "gif": 代码,但生成的 JPEG 完全是白色的。
更新:
我自己修好了。
感谢大家的贡献!
我换了:
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 个参数吗?
-
代码不是我写的,我是菜鸟。我不知道你的问题的答案。对不起,我不能帮你。
-
这实际上都在手册中。 imagecolorallocate - 返回一个颜色标识符,表示由给定 RGB 分量组成的颜色。 对于 alpha 透明度,您需要使用
imagecolorallocatealpha,它确实添加了第 5 个参数:php.net/manual/en/function.imagecolorallocatealpha.php -
@Jeff - 当您自己解决问题时,为什么不写一个答案并接受它作为解决方案?这样一来,您的问题就不再“悬而未决”。