php - ImageMagick 白色到透明背景,同时保持白色对象

标签 php imagemagick

我正在使用 PHP 的 ImageMagick将图像的白色背景变为透明。我将图像 URL 传递给这个 PHP 脚本,它会返回图像。

<?php

# grab the remote image url
$imgUrl = $_GET['img'];

# create new ImageMagick object
$im = new Imagick($imgUrl);

# remove extra white space
$im->clipImage(0);

# convert white background to transparent
$im->paintTransparentImage($im->getImageBackgroundColor(), 0, 3000);

# resize image --- passing 0 as width invokes proportional scaling
$im->resizeImage(0, 200, Imagick::FILTER_LANCZOS, 1);

# set resulting image format as png
$im->setImageFormat('png');

# set header type as PNG image
header('Content-Type: image/png');

# output the new image
echo $im->getImageBlob();

这些转换效果很好。但是,如果我有一个带有白色物体的图像,由于将模糊值传递给 paintTransparentImage(),它不能很好地工作。 ;这就是我清理锯齿状边缘的方式。

这是一个结果示例,注意白色沙发:

enter image description here

如果我没有传递一个 fuzz 值,那么我会得到一个正确的剪辑,但我会留下凌乱的边缘:

enter image description here

我已尝试使用 resizeImage()为了实现所谓的“空间抗锯齿”(将图像放大到非常大 -> 使用 paintTransparentImage() -> 缩小图像),但我没有注意到任何重大变化。

我能做些什么来更好地处理这些真正的白色图像吗?我玩过trimImage()edgeImage() ,但我无法得到我想要的结果。

最坏的情况(虽然不理想),是否有一种方法可以识别图像是否包含一定百分比的特定颜色? IE。如果图像包含 >90% 白色像素,那么我可以运行 paintTransparentImage()模糊值为 0 而不是 3000,这至少会给我一个适当的削减。

谢谢。

最佳答案

解决方案:

先用其他颜色替换白色背景,然后将该颜色更改为透明。

<?php

# get img url
$imgUrl = $_GET['img'];

# create new ImageMagick object from image url
$im = new Imagick($imgUrl);

# replace white background with fuchsia
$im->floodFillPaintImage("rgb(255, 0, 255)", 2500, "rgb(255,255,255)", 0 , 0, false);

#make fuchsia transparent
$im->paintTransparentImage("rgb(255,0,255)", 0, 10);

# resize image --- passing 0 as width invokes proportional scaling
$im->resizeImage(0, 200, Imagick::FILTER_LANCZOS, 1);

# set resulting image format as png
$im->setImageFormat('png');

# set header type as PNG image
header('Content-Type: image/png');

# output the new image
echo $im->getImageBlob();

enter image description here

enter image description here

enter image description here

enter image description here

关于php - ImageMagick 白色到透明背景,同时保持白色对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544467/

相关文章:

php - 解析php数据以仅获取单个数据

visual-studio - 用于 Elastic Beanstalk 配置以安装 Visual C++ Redistributable 的命令

Imagemagick 复合叠加不透明度

svg - 使用 ImageMagick 将 SVG 转换为具有抗锯齿功能的透明 PNG

php - 条件 Laravel Eloquent 关系

php - 为什么我的PHP中的数据不会上传到我的sql服务器?

php - 如果存在则选择值,否则加载默认值

php - Laravel 5 在尝试在 View 中输出时如何处理其中包含空格的数据库列名

python - 使用命令行工具组合多个图像

PHP:使用 GD/Imagemagick 确定通过 Curl 下载的视觉损坏图像(但有效)