Question

Before I start, I just want to note that I am a PHP noob. What I want to do is tint a PNG image to one color. So all transparent pixels will remain transparent, and all non-transparent pixels will be that color. I have searched many sites for this answer but for some reason I can't find what I want.

Here is my first attempt based on different examples I found:

<?php
header('Content-Type: image/png');

$color = $_GET['color'];
$im = imagecreatefrompng($_GET['img']);
$width = imagesx($im);
$height = imagesy($im);
$imn = imagecreatetruecolor($width, $height);
imagealphablending($imn,false);
$col=imagecolorallocatealpha($imn,255,255,255,127);
imagesavealpha($imn,true);
imagefilledrectangle($imn,0,0,$width,$height,$col);
imagealphablending($imn,true);
imagecopy($imn, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imn, IMG_FILTER_GRAYSCALE);


if ($color[0] == '#')
$color = substr($color, 1);

if (strlen($color) == 6)
$r = $color[0].$color[1];
$g = $color[2].$color[3];
$b = $color[4].$color[5];

$r = hexdec($r); 
$g = hexdec($g); 
$b = hexdec($b);

imagefilter($imn, IMG_FILTER_COLORIZE, $r, $g, $b);

imagepng($imn);
imagedestroy($imn);

?>

Essentially a perfect example of what I want can be seen here. The only change will be that instead of black, I want it to be converted to the color the user specifies. Convert non-transparent pixels to black

Thank You

=============================== 10/17/2012 Update

So based on xception's answer, here is the code that I used to execute his script:

<?php

$source = "test.png";
$temp = "temp.png";
$color = "red";
$final = "FINAL.png";

exec("convert $source -alpha extract -threshold 0 -negate -transparent white $temp");
exec("convert $temp -fill $color -opaque black $final");
?>

It worked, however there is a small problem. As illustrated in the screenshots below, there are jagged edges. Any ideas on how to smooth the image so it looks as nice as it did in the BEFORE screenshot?

BEFORE:

BEFORE

AFTER:

AFTER

Était-ce utile?

La solution

Example in 2 steps based on the link you pointed to:

convert <source> -alpha extract -threshold 0 -negate -transparent white <tmp>
convert <tmp> -fill red -opaque black <destination>

replace <source>, <tmp>, <destination> with appropriate file names, replace red with the color you want.

EDIT: shorter version found by question author:

exec("convert $source -threshold 100% +level-colors '#00FF00', $final");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top