2017-04-21 225 views
2

我在PHP中使用ImageMagick来变成透明的图像的白色背景。我将图像URL传递给此PHP脚本并返回图像。ImageMagick白色透明背景,同时保持白色对象

<?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

如果我没有通过一个模糊值,然后我得到一个合适的切割,但我离开我凌乱的边缘:

enter image description here

我已经试过了,用resizeImage(),有什么人被称为“反锯齿”(炸掉像真正的大 - >使用paintTransparentBac kground() - >缩小图像),但我没有注意到任何重大变化。

有什么我可以做的,以更好地处理这些真正的白色图像?我玩过trimImage()和edgeImage(),但是我无法得到结果。

最糟糕的情况,(虽然不是最理想的),有没有一种方法来确定图像是否包含某种特定颜色的百分比? IE浏览器。如果图像包含像90%的白色像素,那么我可以运行paintTransparentImage的模糊值为0而不是3000,这至少会给我一个合适的切割。

谢谢。

+0

解决。编辑后显示解决方案。 – Crayons

回答

1

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

?> 

enter image description here

enter image description here

enter image description here

enter image description here