PHP Error with ImageCreateFromBMP function

Filed Under PHP/MySQL | 2008-10-14, 13:49

This post is for the web/php geeks out there.
I have a page that needs to be able to accept multiple image formats as the users are not to be expected to format their image just right. In short it takes whatever image the user provides and then converts it to a PNG I can use. In an attempt to support as many image formats as possible, I’ve had to jump through a few hoops. Luckily the GD library with PHP has the following functions: imagecreatefrompng, imagecreatefromjpeg, imagecreatefromgif. However what GD does not have built in is imagecreatefrombmp. Boo! But thanks to PHP.net’s users, there’s a function written by DHKold.

So I added this function to my code, and things seem to be working fine. But lately I noticed that my error logs were huge! We’re talking hundreds of megs. I looked into them and one of the main errors flooding my logs was this:

[Tue Oct 14 01:06:39 2008] [error] PHP Warning: unpack() [<a href='function.unpack'>function.unpack</a>]: Type n: not enough input, need 2, have 0 in /usr/www/path/to/my/file.php on line 157

It was repeating itself several hundred times a second. This was not right. I took a look at my code and line 157 was the unpack call in the following block of code:

elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("n",substr($IMG,$P,2));
$COLOR[1] = $PALETTE[$COLOR[1]+1];
}

Looks like 16bit BMPs aren’t really compatible with this function. *grumble grumble* Image formats are not my forte, and I have zero interest in learning about all the various ins and outs. Luckily the PHP user comments come in handy again! domelca writes:

function ImageCreateFromBMP($filename) don't work with bmp 16 bits_per_pixel
change pixel generator for this
elseif ($BMP['bits_per_pixel'] == 16)
{
$COLOR = unpack("v",substr($IMG,$P,2));
$blue = ($COLOR[1] & 0x001f) << 3; $green = ($COLOR[1] & 0x07e0) >> 3;
$red = ($COLOR[1] & 0xf800) >> 8;
$COLOR[1] = $red * 65536 + $green * 256 + $blue;
}

I’ve updated the code in my file and now I’m watching the error logs closely to see if anyone’s images trigger the error again. Why PHP doesn’t provide an official imagecreatefrombmp() I don’t know, but hopefully this fix will help support a few more different images as well as keep my error logs a little smaller. Figured I’d post this to save someone else the hassle of hunting it down.

4 Comments