Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate and save a .png-image in clojure

How do I generate a simple BufferedImage and save it as a png-file in Clojure?

like image 218
claj Avatar asked Jan 20 '23 01:01

claj


1 Answers

I've done something to this manner, briefly like this:

(def bi (BufferedImage. 16 16 BufferedImage/TYPE_INT_ARGB))
(def g (.createGraphics bi))
;; use g
(.drawLine g 0 0 10 10)
(.drawLine g 0 15 15 0)
;; save:
(ImageIO/write bi "png"  (File. "test.png"))

BufferedImage serves the Graphics2D context g and we use ImageIO to do the save.

Example from a project of mine:

(ns minemap.graphics
  (require minemap.core)
  (import java.io.File)
  (import java.awt.Color)
  (import java.awt.image.BufferedImage)
  (import javax.imageio.ImageIO))

(defn draw-png
  "Take width, height, and the map of mines. Save to a file.
  Supposed to take a generate-random-map{,-perc} mapping."
  [width height minemap file]
  (let [block 5 ;block size
        bi (BufferedImage. (* block width) (* block height) BufferedImage/TYPE_INT_ARGB)
        g (.createGraphics bi)]
    (do
      (.setColor g (*colors* :background))
      (.fillRect g 0 0 (* block width) (* block height))
      (doseq [[[x y] high] minemap]
        (.setColor g (*colors* high))
        (.fillRect g (* block x) (* block y) block block))
      (ImageIO/write bi "png" (File. file)))))
like image 104
mike3996 Avatar answered Jan 25 '23 15:01

mike3996