pixfabrik / magrathea

2 stars 0 forks source link

Loading GIF and PNG8 #4

Open iangilman opened 6 months ago

iangilman commented 6 months ago

I figure I'll file a fresh issue for this.

@steffest do you know how to load those formats on a webpage and get their color palette information? Just loading them into an image presumably converts them into 32-bit color and loses the palette.

steffest commented 6 months ago

Yeah, For GIF you can find that code on https://github.com/steffest/DPaint-js/blob/master/_script/fileformats/gif.js

Basically the 11th byte, highest bit indices if the color palette is in the main header or further down on the "frame" data. If it's not an animated gif, it's almost always in the main header. That byte also containts the color count. Then each color is stored as 3 byts RGB values from the 14th byte onwards. (so colorcount * 3 in length)

If the palette is not there, you have to drill down a bit deeper and find the "Image Descriptor" block.

For PNG, that's at https://github.com/steffest/DPaint-js/blob/master/_script/fileformats/png.js PNG uses a "chunck" structure, not very different than IFF. (except in PNG, the size of the chunck comes before the identifier, in IFF it's the other way around) You scan for the "IHDR" block. if the 10th byte in that block is a "3", it's an indexed color PNG. Such a file will then have an "PLTE" chunck with the RGB values of each color.

But on the other hand: I only took a deep dive on those formats because I wanted to write them too, not only read. For reading, I feel maybe you can get away surprisingly well by just reading images the "normal" way, and then just build the palette from whatever color your find on each pixel, mapping them on the fly. (That's what I do in dpaint.js, anyway) As they don't have color cycle information, the exact order of the palette doesn't matter that much and could be mapped on the fly to an already existing palette.

Ah, and if you do want to support .anim brushes, the code how to read those is included in my IFF parser at https://github.com/steffest/DPaint-js/blob/master/_script/fileformats/iff.js

iangilman commented 6 months ago

Wonderful, thank you! ❤️