在clojure中生成并保存.png图像

时间:2011-08-07 14:11:14

标签: clojure image-manipulation

如何生成简单的BufferedImage并将其保存为Clojure中的png文件?

1 个答案:

答案 0 :(得分:9)

我已经用这种方式做了一些事情,简单地说就是这样:

(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投放Graphics2D上下文g,我们使用ImageIO进行保存。

我的项目示例:

(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)))))