Jef*_*eff 20 php gd resize image
我正在使用一个允许用户上传图像的脚本.该脚本调整大小并将图像转换为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;
}
Run Code Online (Sandbox Code Playgroud)
我尝试编辑案例"png":部分以匹配案例"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;
Run Code Online (Sandbox Code Playgroud)
有:
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;
Run Code Online (Sandbox Code Playgroud)
好吧,这个函数来自php。因为我从来没有在 php 上处理过图像,所以我不知道。
因此,图像由三种颜色组成:RGB(红、绿、蓝)。对于 PNG,它还由另一个称为 alpha 的滤镜组成,即透明度
所以,仅对于 PNG,您应该切换imagecolorallocate到imagecolorallocatealpha($file,$i,$i,$i,$i);
这应该使您的图像透明。这能解决您的问题还是您真的需要它们在白色背景下?
编辑: 我还注意到您在所有情况下都使用 imagejpg 函数。将它们切换到对应的函数,即imagepng、imagebmp、imagegif