(ns simpleimg) (import [java.awt.image BufferedImage] [javax.imageio ImageIO] [java.io File]) (def default-bg [0x0F 0x0F 0x0F]) (def default-fg [0xF4 0x7F 0x47]) (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)) (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))})))