Search code examples
swiftimagepngcross-platformstatic-libraries

How to write png images using Swift cross platform


I am writing a little cross-platform raytracer in Swift. At the moment I am stuck at the point writing out the generated image. I searched for some days now for a library but what I found was only the following:

  • writing PNG's using UIImagePNGRepresentation: nope thats iOS only
  • lodepng - a lightweight c lib consisting of only 2 files (.c and .h): looks very promising but it won't link with my swift program - very disappointing
  • libpng: full blown png library that is way too much for my purpose.

The image output is the last brick to the initial raytracing algorithm written in swift. I would be really thankful if anybody has an idea how to accomplish this. Maybe somebody can give helpful advice how to solve this problem.

The other option would be to find a very simple image format for which either a lib exists or for which I can write a Swift algorithm for myself.


Solution

  • I would use netpbm which is a trivial format, then use a third-party converter such as ImageMagick or GraphicsMagick to convert it to final form.

    You can use the netpbm library, or simply write the pixels yourself.

    The format is described here

    A typical PPM file looks like this, where the "P3" magic number means that it is in ASCII format:

    $ cat p3.ppm
    P3 4 4 255
      0  0  0    0  0  0    0  0  0   255  0 255
      0  0  0    0 255 127  0  0  0    0  0  0
      0  0  0    0  0  0    0 255 127  0  0  0
    255  0 255   0  0  0    0  0  0    0  0  0
    

    view of sample PPM image

    If you prefer, you can write a "P6" formatted PPM file, in which the pixels are raw bytes;

    $ od -c p6.ppm
    0000000   P   6  \n   4       4  \n   2   5   5  \n  \0  \0  \0  \0  \0
    0000020  \0  \0  \0  \0 377  \0 377  \0  \0  \0  \0 377 177  \0  \0  \0
    0000040  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0 377 177  \0  \0  \0 377
    0000060  \0 377  \0  \0  \0  \0  \0  \0  \0  \0  \0