Created
February 12, 2012 21:13
-
-
Save lukearno/1810881 to your computer and use it in GitHub Desktop.
Playing with Clojure's Java interop a little bit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;;;;; - baker.clj - ;;;;;;;; | |
; | |
; By Luke Arno <luke.arno@gmail.com> | |
; Proof of concept for "baking" badge data into a PNG, | |
; a la Mozilla Open Badges. | |
(ns baker | |
"Bake badge data into PNGs." | |
(:import (java.io File) | |
(com.sun.imageio.plugins.png PNGMetadata) | |
(java.awt.image RenderedImage) | |
(javax.imageio ImageIO IIOImage) | |
(javax.imageio.stream FileImageOutputStream))) | |
; Default field to put the claim in. | |
(def default-metadata-field "AccoladesClaim") | |
(defn set-metadata | |
"Set a metadata field on a PNG, creating metadata if needed." | |
[^IIOImage image field-name data-string] | |
; Add image metadata object if it doesn't have one. | |
(if (nil? (.getMetadata image)) | |
(.setMetadata image (PNGMetadata.))) | |
(let [metadata (.getMetadata image)] | |
(.add (.tEXt_keyword metadata) field-name) | |
(.add (.tEXt_text metadata) data-string)) | |
image) | |
(defn bake | |
"Bake claim data into a PNG." | |
; Called with no field-name, use default. | |
([^IIOImage image claim-string] | |
(bake image default-metadata-field claim-string)) | |
; Bake the claim string into the image. | |
([^IIOImage image field-name claim-string] | |
(set-metadata image field-name claim-string))) | |
(defn write-image | |
"Write the image to a file." | |
[output-file-name ^RenderedImage image] | |
(let [writer (.next (ImageIO/getImageWritersBySuffix "png"))] | |
(.setOutput writer (FileImageOutputStream. (File. output-file-name))) | |
(.write writer nil image nil))) | |
(defn bake-files | |
"Bake claim string from file into an image." | |
[claim-file original-image-file output-image-file] | |
; Read the data string from a file. | |
; Read the image file and render it into memory. | |
; Pass string and image to bake and write the returned image to a file. | |
(write-image output-image-file | |
(bake (IIOImage. | |
(ImageIO/read (File. original-image-file)) nil nil) | |
(slurp claim-file)))) | |
(defn test-bake [] | |
(bake-files "claim.json" "batter.png" "cake.png")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment