PHP确定图像的背景颜色

时间:2015-04-28 21:06:20

标签: php image

我一直在关注CustomInk的design lab,我很好奇他们如何决定背景颜色是什么颜色。例如,如果我上传Facebook徽标,他们决定从图像中删除蓝色。

enter image description here

但如果我上传一张白色背景的苹果照片,那么他们会以类似的方式移除白色。 (即使白色背景不是主色)

在PHP中使用ImageMagick,我怎样才能完成这项任务?

1 个答案:

答案 0 :(得分:3)

我找到了一种解决方案,可以在图像中查找背景颜色并使用PHP和Imagick将其删除。我不是使用边缘,而是决定使用角来确定要移除哪些颜色,这似乎在大多数时间都在起作用。以下是一些结果。

enter image description here

我能够变成这个

enter image description here

(背景图片是我在Google上找到的白色编织材料的纹理)。但这似乎也很适合处理渐变背景。

enter image description here

这是Vette的图片,原件首先是,然后将所有角落的颜色改为透明,最后一个是从角落开始使用填充。

$Image = new Imagick('vette.jpg');
$BackgroundColors = array(
    'TopLeft' => array(1, 1),
    'TopRight' => array($Image->getimagewidth(), 1),
    'BottomLeft' => array(1, $Image->getimageheight()),
    'BottomRight' => array($Image->getimagewidth(), $Image->getimageheight())
);

foreach ($BackgroundColors as $Key => $BG) {
    $pixel = $Image->getImagePixelColor($BG[0], $BG[1]);
    $colors = $pixel->getColor();
    $ExcludedColors[] = rgb2hex(array_values($colors));
    $Image->floodfillPaintImage('none', 9000, $pixel, $BG[0] - 1, $BG[1] - 1, false);
    //Comment the line above and uncomment the below line to achieve the effects of the second Vette
    //$Image->transparentPaintImage($pixel, 0, 9000, false);
}
$Image->writeImage("vette-no_background.png");