php imagick 将 PNG 转换为 jpg

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6610739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:50:53  来源:igfitidea点击:

php imagick convert PNG to jpg

phppngjpegimagick

提问by rabudde

$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 thisimage. 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).

一切都好起来了。我认为它必须用透明背景做一些事情,这在 JPG 格式中是不可用的。任何人都可以帮助解决这个问题(imagick 没有很好的记录,所以我不知道如何帮助自己)。

回答by rabudde

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');

回答by Bastien

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

另一种将透明 png 转换为 jpg 的方法,如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');

As time moves on, flattenImages()has been deprecated.
Instead of the line above use:

随着时间的推移, flattenImages()已被弃用。
而不是上面的行使用:

$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);

回答by Sander Marechal

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

您可以使用setBackgroundColor将默认背景颜色设置为黑色以外的其他颜色。保存为 JPG 时,PNG 透明度将替换为背景颜色。

Edit: Use it like so:

编辑:像这样使用它:

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

回答by binaryLV

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

尝试添加$image->setBackgroundColor(0xFFFFFF);$image = new Imagick('PNG:image.tmp');