Tuesday, 17 May 2011

Exam tomorrow, let's talk about reading raw pixels to use with GD

I have an exam tomorrow about Distributed Systems and Networks. So what is the best way to spend our time right now? That's right, don't revise and talk about an old problem I had while implementing a script.

So while creating the P3T extractor for PS3 Themes in PHP, I was using PHP's GD functionality to read extracted .gim images, which are basically images that contain raw pixel data, in RGBA format, each 8bits.
Now, RGB was all fine, but the Alpha channel was not so much. Any GD user, who has created images with alpha transparency knows that PHP's imagecolorallocatealpha() function requires a alpha channel of up to 127. this means 7 bits.

But that is not all. Imagecolorallocatealpha() alpha argument sees the alpha argument as 0 being completely opaque, and 127 completely transparent, however, this was exactly the opposite as to a .gim file, where 0 was completely transparent, and 255 was completely opaque.

How do we solve this?
Well, any mathematician would probably see the problem straight away, however, it is a bit more trickier when you would have to figure out how the data is saved. Anyway, after figuring that out, I decided to tackle this problem by taking the extracted data, removing 255 from that, and removing the minus sign (abs(), substr($negative_int, 1) or *-1), and then bit shifting this to the right once.

I settled on the substr() method in the beginning, but later decided to go with the abs() function as this made the code more presentable.

I posted the substr() method on PHP's website (found here), but the abs() function makes this much neater.
This is the code:

Highlighted using GeSHi
  1. <?php
  2. $alpha = abs($alpha - 255) >> 1;
  3. ?>

Of course in this case, $alpha is an int between 0 and 255 (as it is saved like that in .gim files).
Results, if $alpha = 255, $alpha will be 0.


No comments:

Post a Comment