Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Determining and Removing Background Color of Image

Tags:

php

image

I've been looking at CustomInk's design lab and I am very curious as to how they decide what color is the background color. For example, If I upload the Facebook logo, they decide to remove the blue from the image.

enter image description here

But if I upload a picture of an apple with a white background, then they remove the white in a similar fashion. (even though the white background is not the dominant color)

Using ImageMagick in PHP, how could I also achieve this task?

like image 309
Brian Leishman Avatar asked Apr 28 '15 21:04

Brian Leishman


1 Answers

I've found a solution to finding a background color in an image and removing it with PHP and Imagick. I, instead of using the edges, decided to use the corners to figure out which colors to remove, which seemed to be working most of the time. Below are some results.

enter image description here

Which I was able to get to turn into this

enter image description here

(the background image is a texture of a white woven material I found on Google). But this seemed to handle gradient backgrounds pretty decently as well.

enter image description here

This is a picture of a Vette with the original first, then changing all the corners' colors to transparent, and the final is one using fill starting from the corners.

$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[] = sprintf("%6X",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");
like image 146
Brian Leishman Avatar answered Oct 18 '22 23:10

Brian Leishman