How to convert an image to greyscale using PHP
I was trying to find a neat way to grey out some “powered by” logos for a website I’m developing.
I remembered reading about this very thing in .net magazine/august 2009 (i191,p100), which said:
“Sponsor and associate logos can be a challenge for a designer who is making a valiant attempt to create a cohesive website layout. Logos can be contrasting colour schemes and can be displayed at a wide range of different aspect ratios. When faced with this challenge, I recommend greying out the logos and having them appear in their respective colours upon mouse-over. When placing logos next to each other, I’d consider using visual weight versus actual size to determine spacing.”
So, sure we’ve established that it’s a good idea, the question is how to achieve it…
It’s really quite simple, there’s two parts:
- Convert the image to greyscale using PHP.
- Write HTML and javascript that will change the image source on mouseover.
Before I get started, I need to point out that because I’m British, I use “Grey”, instead of the American “Gray”, apart from in the actual code.
I very quickly discovered a number of ways to convert an image from colour to greyscale, however the easiest way appeared to be using the imagefilter() function with the IMG_FILTER_GRAYSCALE greyscale filter which produced the results I was looking for. I found you can also very easily add all sorts of effects to images using PHP.
I kept it simple and wrote a function that would convert an image from jpeg, gif or png to a png greyscale image. I called it imagegray().
It’s very easy to use, you just pass the filename to the function and it will display the image in greyscale. For example:
<?php
$i=isset($_REQUEST[‘i’])?$_REQUEST[‘i’]:”;
if ($i) { imagegrey($i); }?>
Next, it’s onto the HTML, which although isn’t exactly difficult, you may stumble if you’re unsure…
<img onmouseover=”this.src=’image.jpg'” onmouseout=”this.src=’imagegrey.php?i=image.jpg'” src=”imagegrey.php?i=image.jpg” alt=”image” border=”0″>
That’s it, that’s all there is to it.
If you run a large site, for scalability reasons you may wish to involve caching, but for most small sites, this method is quick and effective.
Enjoy!
Warning: Declaration of Social_Walker_Comment::start_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::start_lvl(&$output, $depth = 0, $args = Array) in /Users/wade/Sites/hm2k.org/wp-content/plugins/social/lib/social/walker/comment.php on line 18
Warning: Declaration of Social_Walker_Comment::end_lvl(&$output, $depth, $args) should be compatible with Walker_Comment::end_lvl(&$output, $depth = 0, $args = Array) in /Users/wade/Sites/hm2k.org/wp-content/plugins/social/lib/social/walker/comment.php on line 42
What about transparent PNG? are they recommended?