Ray Tracing 002Other Image Formats

Summary

  • Explored options to save generated images in other file formats.
  • stb_image.h in C++.
  • Pillow and tkinter in Python.

stb_image.h

The "stb_image.h" single-file library makes it easy to write and convert images to other file formats. The simplicity of the PPM format is great, but sometimes it makes more sense to save the image in a web-friendly format and avoid additional steps to convert the image.

Click to view C++ source code
Click to view Makefile

Python and Pillow

Pillow is a fork of the Python Imaging Library (PIL) and makes it very easy to create, load, edit and save image files. It also features a show() function that opens the image in the default viewer automatically.

The source code for the previous PPM version didn't require a lot of changes: just a few lines to import the Image library, create an empty image with the desired size, load this image into a pixel variable, update the pixels with the calculated RGB colors, and finally, save the image file.

Click to view Python source code

Python, Pillow, and tkinter

Tkinter, or "Tk interface" is the standard Python interface to the Tcl/Tk GUI toolkit and provides modules for dialog boxes, color choosers, mouse events, etc. This example below simply displays the image in a window, but tkinter could be used to build this out to a more interactive app.

To draw the image on the canvas, I could either draw each pixel individually using the create_line() function, or use the Pillow Image object and fill the canvas with the create_image() function instantly. When I tested this, create_line() took significantly longer and the window didn't respond very well anymore. The Image object was the way to go there.

Click to view Python source code

The complete examples are also available in my ray tracing repo.

Links