Making images transparent using Imagick – enter the pixel iterator

Friday July 13th, 2012

So we have this image, and we want to set it to be 75% transparent using Imagick. This sounds simple enough, doesn’t it? Perhaps we are trying to create a watermark, or we just want to fade the image for some reason. So here is our source image.

If you glanced at the PHP manual for Imagick you may have found this method called setImageOpacity. Right on! It takes a float value between 1 and 0 where 1 is fully opaque and 0 is fully transparent. Lets give it a whirl.


Could not embed GitHub Gist 3107242: Bad credentials

WTF just happened? Now the image has a white border, and a black background? This is bad. I can explain the black background. What just happened is we told Imagick to set the Alpha value of every single pixel in the image to be exactly 0.25. Areas that had no colour before still have none, so now we see translucent black where before there was “nothing”. However I cannot offer a single explanation for the white border, that little artifact has eluded my reasoning for quite some time.

Enter The Pixel Iterator

But, we can fix this. More to the point, we can do it correctly ourselves. This is where the pixel iterator comes in. Basically what we need to do is open the image, and then loop over every pixel in it. The point of doing this is we can inspect each pixel to see if it already has transparency, and if it does make it more transparent than it was by the percentage we wanted.

To do this, we use the getPixelIterator() method which will hand us an iterator for the image. This is not how it technically works on the inside, but think of this as an index or array of all the rows (Y values) in our image. We can loop over every row in our image to access the array of columns (X values) in that row. Then we can loop over all the columns to directly access that exact pixel.

Technically we just iterated over an iterator iterator. If you have a beer within arms reach I think the standing rule is you must now take two drinks. Maybe three.

Could not embed GitHub Gist 3107329: Bad credentials

Tada. By checking each pixel and making it more transparent than it already was (assuming it was not already fully transparent) we have correctly made this image usable for ghosting or watermarking.


Comment by Klaus on Thursday October 17th at 2:24am
Thanks! That really saves my day and works like a dream. I tried to make a semi-transparent border around image-uploads with different sizes. But I failed because of the installed version of imagick on our server. Its not the newest version. So setStrokeAlpha and setImageOpacity didnt work. But your solution did it :-)

Thanks from Germany
One Response to “Making images transparent using Imagick – enter the pixel iterator”
Write a Comment