With PHP, how do I colorize a PNG while preserving transparency?

Posted on 2009-02-19
Medium Priority
Last Modified: 2013-12-20
I have been searching for a way to dynamically colorize png images using PHP.  The images have transparency that must be preserved (ie. I don't want anything that is transparent to become colorized).  I have searched through the PHP-GD help files and online, but I can't seem to put anything satisfactory together.

Put another way, can you write PHP code that changes the attached png from green to blue while preserving the detail and alpha channel?

A couple of caveats:

1) I can't use the GD function 'imagefilter' because it is disabled in Ubuntu 8.10 and I don't want to recompile PHP from source (and risk destruction of my current working local web server).  Any other GD functions that don't have the same restrictions as 'imagefilter' are fair game.
2) I can't use ImageMagick because of restrictions imposed by my web hosting plan.
Question by:jzierse
  • 5
  • 4

Expert Comment

ID: 23687951
You might be able to use this function which I found here http://www.myphpcave.com/image-manipulation/colorize-change-color-of-images-using-php-and-gd-library-php-5-version/

function colorize_image($image, $color = '0000FF', $contrast = 0) {
	if (!$image) { return false; } # File error checking
	# Let's fix the color hex, just in case the # was added
	$color = str_replace('#', '', $color);
	# Let's keep the transparency of the PNG or GIF file
	imagealphablending($image, true);
	imagesavealpha($image, true);	
	# Convert hex color into RGB values
	$r = hexdec('0x' . $color{0} . $color{1});
	$g = hexdec('0x' . $color{2} . $color{3});
	$b = hexdec('0x' . $color{4} . $color{5});
	# Let's apply the filters to colorize and contrast the image
	imagefilter($image, IMG_FILTER_COLORIZE, $r, $g, $b);
	imagefilter($image, IMG_FILTER_CONTRAST, $contrast);
	# Return the GD image object
	return $image;

Open in new window


Author Comment

ID: 23688346
Unfortunately, as I stated in caveat one, I need a solution that doesn't use the imagefilter function, which this method does.

Thanks for the reply.

Any other suggestions?

Author Comment

ID: 23716601
I still haven't found a solution to this particular problem.  Any thoughts?

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

LVL 40

Expert Comment

by:Richard Quadling
ID: 23778089
Not something I've tried directly, but it could be possible to read the palette chunk from the PNG file, edit it and then re insert it back into the PNG file.

This would require no special extensions.


http://www.w3.org/TR/PNG/ contains the w3c's spec on the PNG file format.

http://www.w3.org/TR/PNG/#11PLTE has info about the palette.

As it looks like it is not compressed, it may be really simple.

Is this something you could persue/use?

Author Comment

ID: 23778474
I hadn't considered modifying the PNG data directly, but that is definitely an interesting avenue to explore.   I will experiment with it and get back to you with the results.

I was hoping there would be something to be done with the other GD functions such as 'imagecolorset', 'imagesavealpha', 'imagesetpixel', etc., but if I can parse the PNG data in a relatively straight forward manner, your suggestion will work great.

Author Comment

ID: 23796552
Unfortunately, this doesn't seem to be an avenue that I will be able to use.  I tried searching my PNG files for the appropriate PLTE byte chunks, but I can't seem to find them consistently (or at all, actually).  I believe this is because the PLTE section is not required for TrueColor images with Alpha (http://www.w3.org/TR/PNG/#11PLTE).

 Are there any other ideas that involve the GD functions 'imagecolorset', 'imagesavealpha', 'imagesetpixel', etc.?
LVL 40

Expert Comment

by:Richard Quadling
ID: 23796738
The other way is a brute force way to read every pixel and write every pixel with the new colour.


Author Comment

ID: 23797851
My understanding is that will destroy the the detail of the image.  For instance, in the image I posted, if I simply set every pixel to blue I will end up with a solid blue rectangle.

I'm assuming that there is some sort of blending required, I just don't know how to accomplish that with PHP code.

Is there a possiblility of someone posting code that would change the attached PNG file from green to blue while retaining the transparency and detail?
LVL 40

Accepted Solution

Richard Quadling earned 1500 total points
ID: 23803435
Of course. I meant you would have to process each pixel individually. It isn't really a PHP issue, but one of colour maths. How do you want to process the image.

Personally, I would make the image monochrome. A grey-scale image is much easier to colour (from someone who doesn't understand colours completely).

So, say you want to add a colour of 75% red ( rgb(192, 0, 0)) for example.

Then each pixel would be read and I think the maths would be SOMETHING like ...

new_red_value = greyscale_value * red_overlay_value / 256
new_green_value = greyscale_value * green_overlay_value / 256
new_blue_value = greyscale_value * blue_overlay_value / 256

Now you would set the pixel colour to the new rgb values.

I think the alpha channel would/should be unmodified.
LVL 40

Expert Comment

by:Richard Quadling
ID: 23814973
Thanks for the points. I'd like to know how you get on. An interesting question.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
Measuring Server's processing rate with a simple powershell command. The differences in processing rate also was recorded in different use-cases, when a server in free and busy states.
The goal of the tutorial is to teach the user how to remove a natural vignette your photos and how to add vignette to your photos.
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question