我正在使用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(),它不能很好地工作;这就是我如何清理锯齿状的边缘。
以下是结果示例,请注意白色沙发:
如果我没有通过模糊值,那么我会得到一个合适的剪切,但我留下了凌乱的边缘:
我尝试使用resizeImage()来实现所谓的“空间抗锯齿”#39}。 (夸大图像真的很大 - &gt;使用paintTransparentImage() - &gt;缩小图像缩小),但我没有发现任何重大变化。
我能做些什么来更好地处理这些真正的白色图像?我曾与trimImage()和edgeImage()玩过,但我无法在之后得到结果。
最糟糕的情况,(虽然不理想),是否有一种方法可以识别图像是否包含某种特定颜色的百分比? IE浏览器。如果图像包含> 90%的白色像素,那么我可以运行paintTransparentImage(),其模糊值为0而不是3000,这至少会给我一个合适的切割。
感谢。
答案 0 :(得分:3)
<强> SOLUTION:强>
首先用其他颜色替换白色背景,然后将该颜色更改为透明。
<?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();
答案 1 :(得分:-1)
您可以尝试执行exec命令。它为我工作。 您可以参考this链接
<?php
$rand_new = rand();
$target_dir = 'yourFolder/';
$imageName = 'yourImage';
$image = $target_dir.$imageName;
$imageFileType = strtolower(pathinfo($image,PATHINFO_EXTENSION));
$new_image = time().".png";
exec("convert $image -fill none -fuzz 10% -draw 'matte 0,0 floodfill' -flop -draw 'matte 0,0 floodfill' -flop $new_image");
?>