Imagick for PHP中的透明到白色 [英] Transparent to white in Imagick for PHP

查看:438
本文介绍了Imagick for PHP中的透明到白色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个透明背景的png图像,我想将其转换为带有白色背景的jpg图像.

I have a png image with a transparent background and I want to convert it to a jpg image with a white background.

代码基本上是这样的:

$image = new Imagick('transparent.png');
$image->writeImage('opaque.jpg');

但这会创建黑色背景jpg.我一直在努力寻找最糟糕的文档,以试图找到一种将透明色转换为白色而无济于事的方法.

But that creates a black background jpg. I've been struggling with the worst documentation ever trying to find a way to convert the transparent to white to no avail.

修改: 好吧,我尝试了马克·B的想法,并使其付诸实践.

Edit: Well, I tried Marc B's idea and kind of got it to work.

$image = new Imagick('transparent.png');
$white = new Imagick();

$white->newImage($image->getImageWidth(), $image->getImageHeight(), "white");
$white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0);
$white->writeImage('opaque.jpg');

$image->destroy();
$white->destroy();

现在的问题是,它总是导致脚本出现段错误.

The problem now is, it always causes the script to segfault.

推荐答案

flattenImages()实际上有效.

但是请记住,它不会修改给定的\Imagick()对象,但是会返回一个新对象:

But keep in mind that it doesn't modify the given \Imagick() object but returns a new one:

$image = new \Imagick('transparent.png');

// Need to use the result of $image->flattenImages() here!
$image = $image->flattenImages();
$image->writeImage('opaque.jpg');

flattenImages()默认为背景色white.如果要使用其他背景色,则必须在加载图像前 进行设置:

flattenImages() defaults to the background color white. If you want to use another background color you have to set it before loading the image:

$image = new \Imagick();

// Needs to be called before the image is loaded!
$image->setbackgroundcolor('green');
$image->readimage('transparent.png');

$image = $image->flattenImages();
$image->writeImage('opaque.jpg');

通常,对于函数调用的顺序(就像convert及其命令行上的参数一样),Imagick API非常合理.因此请务必检查顺序是否正确.

In general the Imagick API is very sensible when it comes to the order of function calls (just like convert and its parameters on the command line) so always check if your order is correct.

祝你好运!

编辑2016年4月:

$image->flattenImages() 已弃用,应替换为:

$image->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN)

很难找到确切的信息,但这似乎适用于PHP> = 5.6.

It's hard to find exact informations about this, but it seems that this applies to PHP >= 5.6.

感谢小费!

这篇关于Imagick for PHP中的透明到白色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆