PHP imagecolorallocation producing incorrect color?

A problem with a simple explanation and fix that’s surprising hard to find an answer for on google. In php, when working with certain images imagecolorallocate() will not return the color you want, and instead return any old color. It’s a rather frustrating problem on the surface, as your code is correct and the result the server ives you is not. but after a little troubleshoot the answer hit me in one of those moments of clarity you hear alcoholics talk about. It’s all a problem of the images color allocation table.

See, the problem is that an image in certain formats (GIF and PNG (8 bit) and there are probable other, less common formats that are susceptible) Store every color in the image in a table. This is what the command imagecolorallocate modifies to give you your color. Specifically it ads one to the end of the table and return it back to you. This is the root of the problem. See, if the image is full color (relative to the limited number of colors they can have) imagecolorallocate can’t add a new color to the images color allocation table, and instead returns a random color (which I’m sure is not random, it’s probably just the last color in the table). So thats the problem, whats the solution?

Simple, remove a color from the color table. Not I suggest doing this prom Photoshops “Save for Web and Devices..” feature as it will be able to re-jigger the color table to still look good, randomly pulling a specific color and turning it black (which can be done entirely from PHP) runs the risk of ruining the image. You can over-ride the Photoshop palet size option simple by typing in the box next to it, 255 will leave you one more color to fill, if you want to use multiple colors then you need to adjust you images pallet size accordingly.