将JPG转换为PNG,并在其中设置透明颜色


transform a jpg into png and make a color transparent in it

在PHP中,我试图处理图像,也就是说,我试图在jpg文件中使周围的颜色透明。顺便说一下,我正在使用GD库。

我可以通过使用imagecreatefromjpeg和imagepng函数将其转换为png直接输出图像。但是我找不到使指定颜色透明的方法。此外,有些图像在保存过程中创建的黑色图形周围有浅灰色的伪影。我能把这些也算进去吗?

我有点迷路了。我找到了一些答案,使颜色透明的图像,但我不知道如何首先转换图像不保存到服务器,然后处理它。

任何想法?

编辑:这是我到目前为止的代码。我设法使一个指定的颜色透明,但我不能使它检测到周围的一个。

大多数情况下,图像将被关闭,因为它们将是徽标或文本,以允许的图像格式保存。所以我不认为我在渐变上有什么大问题,但如果我能设法操纵周围渐变的透明度,如果有的话,比如投影,那就太好了。

是否还有任何方法来检测png/gif图像是否已经透明?我的代码现在将这些文件的透明部分绘制成黑色。

$file = 'images/18.jpg';
$specs = getimagesize($file);
if($specs[2] == 1) $img = imagecreatefromgif($file);        //gif
elseif($specs[2] == 2) $img = imagecreatefromjpeg($file);   //jpg
elseif($specs[2] == 3) $img = imagecreatefrompng($file);    //png
else exit('unsupported file type!');
$newimg = imagecreatetruecolor(imagesx($img), imagesy($img));
// create a new image with the size of the old one
imagecopy($newimg,$img,0,0,0,0,imagesx($img),imagesy($img));
// copy the old one
imagedestroy($img);
// free the memory
$white = imagecolorallocate($newimg,255,255,255);
imagecolortransparent($newimg,$white);
// make white pixels transparent
header('Content-Type: image/png');
imagepng($newimg);
imagedestroy($newimg);
// and finally output the new image

可以通过imagecolortransparent函数设置透明颜色