Simple binary images in JVM Clojure
I've been looking into algorithmic art a bit, recently. I think I'd like to give it a go. The problem is that I don't know anything. It's tempting to learn with a high-level library like Quil to get moving quickly but I find the choice paralysis unbearable (not to mention how much complexity it offers in its own right). I'd much rather wallow in the mud to keep terra firma within arm's reach.
So here's my attempt to corral the complexity a bit by paring image generation down to the bare essentials. I'll use this as a starting point for a few other articles that are in the works.
All I want is to create an image of a certain size (in pixels), to set pixels to particular colors, and to save that image to a file. To be sure, standard Java can do a lot more, with strokes, shapes, paints, fonts, etc…. I don't need any of that yet. Just give me a raster buffer and a way to color its pixels.
If you browse thru the docs for the java.awt package, you'll quickly find the Image
class. It's abstract, so we need to find something more concrete. Comparing the two listed
subclasses, BufferedImage and VolatileImage, it seems like the former is the
straightforward one. So we check out the constructors and find even the simplest form of the
constructor wants us to make one more decision: what type of image? How many bits per pixel,
and what do they mean?
Luckily, this is actually an opportunity for reducing complexity. The simple mental model I
have of each pixel storing separate RGBA values could be even simpler! What if we choose our
color palette beforehand and store only the index number of the corresponding color? What a
wonderful idea! The thought of having to choose colors from a vast 4-byte-per-pixel
landscape was giving me an agoraphobic panic attack. Using this method gives me a nice
excuse (file size efficiency) to severely limit the available choices as well as my own
sense of looming dread. So as we scan down the Field Summary for the available image types,
we can breathe a sigh of relief on discovering that TYPE_BYTE_BINARY lets us do just
that. If we pick only two colors, each pixel will only occupy a single bit!
(import [java.awt.image BufferedImage]
[javax.imageio ImageIO]
[java.io File])
(Separating the import form here because of how org-babel processes these blocks.)
(let [img (BufferedImage. 100 100 BufferedImage/TYPE_BYTE_BINARY)
filename "blank.png"]
(ImageIO/write img "png" (File. filename))
filename)
Don't gaze at it for too long, lest it gaze back.
How to draw on it? Every BufferedImage comes with its very own WritableRaster to set
individual pixels or rectangles. 1
(let [img (BufferedImage. 100 100 BufferedImage/TYPE_BYTE_BINARY)
raster (.getRaster img)
filename "diagonal.png"]
(dotimes [i 100]
(.setSample raster i i 0 1))
(ImageIO/write img "png" (File. filename))
filename)
This constructor makes a default 1-bit white on black color model. Next up is the version
that takes an IndexColorModel, so let's create one. Choosing #F47F47 as the foreground
color and #0F0F0F for the background:
(def default-bg [0x0F 0x0F 0x0F])
(def default-fg [0xF4 0x7F 0x47])
The quirk is that IndexColorModel wants each channel in a byte-array together. It'll
take up to 16 colors/4 bits. We can massage the above colors into place like so:
(import [java.awt.image IndexColorModel])
(defn make-palette
"Constructs an IndexColorModel from up to 16 colors in the form [r g b a]"
[& colors]
(let [size (count colors)
bits (condp > size
3 1
5 2
9 3
17 4
(throw (IllegalArgumentException. "16 colors or fewer, if you please")))
[r g b a] (->> colors
(reduce #(map conj %1 (map unchecked-byte %2))
[[] [] [] []])
(map byte-array))]
(IndexColorModel. bits size r g b a)))
(def default-palette (make-palette default-bg default-fg))
With that done, we have enough to make a lil canvas object. Add in a few bits and bobs for completeness.
(import [java.awt.image WritableRaster])
(defn make-canvas
([height width] (make-canvas default-palette height width))
([palette height width]
(let [img (BufferedImage.
width height
BufferedImage/TYPE_BYTE_BINARY
palette)
raster (.getRaster img)]
{:height height
:width width
:img img
:set-pixel! (fn set-pixel!
([row col]
(set-pixel! row col 1))
([row col slot]
(.setSample ^WritableRaster raster (int col) (int row) 0 (int slot))))
:set-pixels! (fn set-pixels!
([row col height width]
(set-pixels! row col height width 1))
([row col height width slot]
(.setSamples ^WritableRaster raster
(int col) (int row) (int width) (int height)
0
(int-array (* width height) slot))))
:save! (fn [filename]
(let [filename (str filename ".png")]
(ImageIO/write img "png" (File. filename))
filename))})))
And that's the ball game. Now we have everything we need to unleash a devastating art algorithm.
(let [{:keys [set-pixel! set-pixels! save!]} (make-canvas 100 100)]
(dotimes [i 100]
(set-pixel! i i)
(set-pixel! i (- 99 i)))
(set-pixels! 25 25 50 50)
(set-pixels! 30 30 40 40 0)
(save! "x-squared"))
It's so perfectly cromulent, it embiggens my entire soul. 🥹
At this point, this article is a proper clojure namespace we can import at our leisure in future articles. It's got its own deps.edn and the code we wrote along the way gets tangled into a source file on disk that we can load the normal way.
Footnotes:
I'm returning the filename each time so org-babel renders it in HTML.



