我正在使用 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(),它不能很好地工作。 ;这就是我清理锯齿状边缘的方式。
这是一个结果示例,注意白色沙发:
如果我没有传递一个 fuzz 值,那么我会得到一个正确的剪辑,但我会留下凌乱的边缘:
我已尝试使用 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();
关于php - ImageMagick 白色到透明背景,同时保持白色对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544467/