使用PHP将JPEG转换为透明PNG

Max*_*ins 6 php png gd jpeg image-manipulation

我有很多JPEG图像,我想用PHP转换为PNG图像.JPEG将由客户上传,因此我不能相信它们以确保它们的格式正确.

我也想让他们的白色背景透明.

PHP有没有我可以用来实现这个功能?

Max*_*ins 8

经过几天尝试不同的解决方案并进行更多的研究,这是我发现为我工作的.

 $image = imagecreatefromjpeg( 'image.jpg' );
 imagealphablending($image, true);
 $transparentcolour = imagecolorallocate($image, 255,255,255);
 imagecolortransparent($image, $transparentcolour)
Run Code Online (Sandbox Code Playgroud)

imagealphablending($image, true);很重要.

使用imagesavealpha($f, true);前面的答案肯定不起作用,似乎实际上阻止你使背景透明...

使用正确的标题输出透明图像.

<?php
     header( 'Content-Type: image/png' );
     imagepng( $image, null, 1 );
?>
Run Code Online (Sandbox Code Playgroud)


gen*_*sis 6

$f = imagecreatefromjpeg('path.jpg');
$white = imagecolorallocate($f, 255,255,255);
imagecolortransparent($f, $white);
Run Code Online (Sandbox Code Playgroud)

更多细节在这里

  • 假设这会起作用,请注意JPG是一种有损格式.这意味着颜色可能稍微偏离,特别是在边缘周围以及颜色从白色变为另一种颜色的地方.寻找纯白色可能无法找到您想要透明的所有像素. (6认同)