我有一个透明背景的PNG图像,我想创建具有白色背景的渐进式JPEG,任何解决方法都非常受欢迎,是否可以从PNG创建PJPEG?
下面是我的解决方法,我只是想知道这是否是正确的方法。
$filePath = 'a.png';
$savePath = 'a.jpeg';
$colorRgb = array('red' => 255, 'green' => 255, 'blue' => 255);
$img = @imagecreatefrompng($filePath);
$width = imagesx($img);
$height = imagesy($img);
$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);
imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);
imageinterlace($backgroundImg, 1);
imagejpeg($backgroundImg, $savePath, 80);
答案 0 :(得分:1)
header('Content-Type: image/jpeg');
$image = new Imagick();
$image->readImage("image.png"); //add your png file
$image->setImageBackgroundColor('#FFFFFF'); //add your background color
$image = $image->flattenImages(); //flatten the image
$image->setImageFormat('jpg'); //set the format
$image->writeImage('image.jpg'); //save it
echo $image;
使用Imagick将完成这项工作:)
注意: 在php.ini中添加extension=imagick.so
,如果默认情况下未启用Imagick。
答案 1 :(得分:0)
这是在我的项目中尝试过的一次,希望它有所帮助:
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im === false) {
die("imagecreatefromstring failed");
}
imageinterlace($im, true);
imagejpeg($im, 'new.jpg');
imagedestroy($im);