i am trying to to colorize a black and white picture on my server.

i have tried doing this with multiple methods and the only one that kind-of-works is gd imagefilter via filter IMG_FILTER_COLORIZE.

it does kind of colorize the image in exactly the same color that i want, but it loses all the details on the image, as if it just trimmed black dots that were not black enough and thinned all the black lines, making them almost invisible. here is what i'm talking about:

original image colorized picture

this result was achieved with this code

$im=imagecreatefromjpeg($orig_file);
imagefilter($im, IMG_FILTER_COLORIZE, 71, 92, 10);
imagejpeg($im, $output_file, 95);

why is this happening? are there any other methods how i could colorize the image? my original image is quite large and i can't iterate over it as it is too slow; that's why i'm trying to use a library that would do this

有帮助吗?

解决方案

i have managed to achieve the desired result with help of Imagick and compositeImage. here is the result

original picture desired result

how i achieved it is kind of a trick that works only in a very specific condition- which is the need to have the background white and only black/gray objects in front (or the exact opposite). this technique wouldn't work on a background with transparency

the idea is to have 2 layers- underneath is the layer with original grayscale image and the top layer- fully filled with the desired color. then you composite these images using "COMPOSITE_LIGHTEN" (you might use other methods, like darken for example- if you have white objects on a black background)

this is the code

$base_color="#475c0a";
$im=new Imagick($orig_file);

$im2 = new Imagick();
$im2->newImage($im->getImageWidth(), $im->getImageHeight(), new ImagickPixel($base_color) );

$im->compositeImage($im2, Imagick::COMPOSITE_LIGHTEN, 0, 0);

$im->writeImage($new_image_path);

hope this will help someone out

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top