Post · 2 min read· p. 290

mini PNG 64x64 serializer

This is a very niche use case, but one I encountered recently - if had to export little 64x64 pixel thumbnails in PNG format, as a rather isolated task in a system module that otherwise didn't need image import/export support. So instead of importing something large like libpng or stb_image, I implemented this tiny cute thing:

#include <stdio.h> #include <stdint.h> bool write_png_64x64( FILE* fp, const uint32_t pixels[64*64] ) { static constexpr uint8_t binary[] = { 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00, 0x00,0x0d,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x40, 0x00,0x00,0x00,0x40,0x08,0x06,0x00,0x00,0x00,0xaa, 0x69,0x71,0xde,0x00,0x00,0x40,0x4b,0x49,0x44,0x41, 0x54,0x08,0x1d,0x01,0x40,0x40,0xbf,0xbf,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82 }; if( !fwrite(binary,48,1,fp) ) return false; for( int i=0; i<64; i++ ) { if( !fwrite(binary+48, 1,1,fp) ) return false; if( !fwrite(pixels+64*i,256,1,fp) ) return false; } if( !fwrite(binary+48,20,1,fp) ) return false; return true; }

This is using PNG without compression, which for small resolution images it actually produces smaller files than with compression. For large files you probably do want compression, in which case the code would get a bit larger (but not by a lot if done carefully). The code just emits the PNG header, the IHDR chunk, one IDATA chunk and the IEND chunk (more info in the Wikipedia article). On the other hand, while it would be easy to generalize it to any image resolution (actually my first iteration of this code was generic), here I hardcoded it all to my use case because I really did NOT want anybody to find the function and think they could use it for general PNG export.