Wednesday, February 17

Capturing a screenshot, displaying an image, and load/saving an image in Clojure

The following functions perform a screenshot, or capture a region of the screen, and then provide a method to display the captured image in a new window or load/save to disk.

Note: I'd like to thank hoeck (from the Clojure IRC channel) for writing the display-image function.

(defn display-image
"Displays an image in a new window"
(let [frame (doto (javax.swing.JFrame. "Display Image")
(.setBounds 0 0 (. image getWidth) (. image getHeight))
(.setVisible true))
cv (proxy [java.awt.Canvas] []
(paint [g] (. g drawImage image nil nil))
(update [g] (. g drawImage image nil nil)))]
(.add (.getContentPane frame) cv)))

(defn capture-image
"Captures an image of a section of the primary screen"
[from-x from-y x-size y-size]
(let [rob (java.awt.Robot.)
rect (java.awt.Rectangle. from-x from-y x-size y-size)]
(. rob createScreenCapture rect)))

(defn grab-screen
"Returns an image of the entire primary screen"
(let [my-scr (.. java.awt.Toolkit (getDefaultToolkit) (getScreenSize))]
(capture-image 0 0 (. my-scr width) (. my-scr height))))

(defn save-image
"Save an image to disk as jpg"
[image filename]
(javax.imageio.ImageIO/write image "jpg" ( filename))

(defn load-image
"Read a jpg from disk"
(javax.imageio.ImageIO/read ( filename)))

1 comment:

TheBusby said...

Eek, I better figure out better way to display code it looks like...