Topic: Writing a PNG image file in C or Java

For those that may be interested, here are some references and code for writing a PNG image file in C or Java.  Perhaps someone might be interested in converting them to Fortran so that SF's BMP file is not the only image file.

References from the web:

C++ Code:

Tiny PNG Output is a small standalone library, available in C and C++, which takes RGB8.8.8 pixels and writes 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 LGPLv3+.

In ~260 lines of C++ code or ~260 lines of C 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, avoiding 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.

Java Code:

This Java library takes an array of pixel values and writes it as a PNG image file. My simple implementation is inefficient in many ways, but it behaves correctly and produces legal PNG files. The whole program is only about 140 lines of code long.

The PNG file format is widely supported for because it flexibly supports many color formats and has compression built in. (By contrast, the Windows BMP format has no compression, and the GIF format was patented in the past.) When I read the PNG file format specification, I realized that writing a basic compliant encoder wasn’t too difficult and wouldn’t take too much code.

Re: Writing a PNG image file in C or Java

The real issue with saving a PNG file is that access to the bits on the screen itself is complicated.  Saving a BMP is trivial using a few Windows API commands.  However, accessing the underlying bytes of said bitmap for writing as a PNG file is far more complicated. It's also unnecessary to rewrite in Fortran; a simple wrapper around the C code using the ISO_C_BINDING module should be sufficient if access to the screen's image were available.

This same process could, of course, be done manually by looping through and querying the color at every pixel to build the in-memory array representing the image for passing into the PNG routines.  However, it would be slow.

Jeff Armstrong
Approximatrix, LLC