php imagick convert PNG to jpg

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

$image = "[...]"; //binary string containing PNG image $file = fopen('image.tmp', 'wb'); fputs($file, $image); fclose($file); $image = new Imagick('PNG:image.tmp'); $image->thumbnailImage($width, $height); $image->setImageFormat('jpg'); $image->setCompressionQuality(97); $image->writeImage('image.jpg');

The above doesn't work and gives me a black image for this image. When doing instead

[...] $image->setImageFormat('png'); $image->setCompressionQuality(97); $image->writeImage('image.png');

all is fine again. I think it has to do something with transparent background, which isn't available in JPG format. Can anyone help to solve this (imagick isn't documented very well, so I don't know how to help myself).

回答1:

Found a solution:

$white=new Imagick(); $white->newImage($width, $height, "white"); $white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0); $white->setImageFormat('jpg'); $white->writeImage('image.jpg');


回答2:

Another way to convert transparent png to jpg, as mentioned in Imagick::flattenImages:

$im = new Imagick('image.png'); $im->setImageBackgroundColor('white');  $im->flattenImages(); // This does not do anything. $im = $im->flattenImages(); // Use this instead.  $im->setImageFormat('jpg'); $im->writeImage('image.jpg');


回答3:

You can use setBackgroundColor to set the default background color to something else than black. The PNG transparency will be replaced by the background color when saving to JPG.

Edit: Use it like so:

$img->setBackgroundColor(new ImagickPixel('#FFFFFF'));


回答4:

Try adding $image->setBackgroundColor(0xFFFFFF); after $image = new Imagick('PNG:image.tmp');



转载请标明出处:php imagick convert PNG to jpg
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!