Project Nayuki


Tiny PNG Output (C)

Tiny PNG Output is a small standalone C library that writes a raw RGB24 image as a PNG file. The image data can be fed to the writer one pixel at a time, a row at a time, or the complete image at once. Licensed as GPLv3+.

In ~260 lines of code, this library implements these key components: PNG header writer, PNG chunk writer, DEFLATE uncompressed encoder, CRC-32, Adler-32. The library is entirely self-contained and does not use the typical PNG tools like libpng and zlib.

The code has been tested on x86 and x86-64, and is expected to work on other platforms as well. It should work on 32-bit embedded microcontrollers but might not work on 8-bit CPUs. Applications for this library include writing PNG files to disk, and generating PNG files on the fly to write to a network socket (e.g. HTTP connection).

The algorithms are carefully designed to behave correctly for all inputs that are below the image size limit of ~700 megapixels. Specifically: Let m = (3 × width + 1) × height. Let n = m + ceil(m / 65535) × 5 + 6. The algorithm requires width and height to satisfy n < 231.

Remember, this library optimizes for simplicity, low line count, absolute correctness, and platform portability. It does not optimize for having many features (such as palette, transparency, interlacing, gamma, etc.) or for file size (in fact it writes uncompressed PNG files). The files generated by Tiny PNG Output are always correct, but inefficient in storage space.

Source code

Complete package: TinyPngOut.zip

Contains: TinyPngOut.h, TinyPngOut.c, simplepng.c, mandelbrotpng.c, COPYING.txt.

If you download this ZIP, you can ignore the individual files listed below.

Core library: TinyPngOut.h

The C header file. Contains a data structure, an enum of error codes, and public function prototypes. Contains documentation for the functions and code snippets showing example usage.

Core library: TinyPngOut.c

The C source code file containing the function implementations (both public and private ones).

Sample application: simplepng.c

A simple demo program that writes a hard-coded 3×2 image, which shows the primary and secondary RGB colors.

To compile and run: gcc -o simplepng simplepng.c TinyPngOut.c && ./simplepng

Sample application: mandelbrotpng.c

A demo program that computes an image of the Mandelbrot set on the fly, buffering and writing one line at a time. (This shows that it’s not necessary to produce the whole image before starting to write the output PNG file.)

To compile and run: gcc -o mandelbrotpng mandelbrotpng.c TinyPngOut.c -lm && ./mandelbrotpng

Although the code is designed for C, it should work just fine when compiled as C++ code too.

License: GNU Public License v3.0+ (COPYING.txt)