Making image thumbnails in Clojure
I'm making a new website (in Clojure of course) and I have a need to resize uploaded images to make thumbnails. At first I tried to use JMagick because I'm familiar with ImageMagick already and it seemed like an OK library. But on the crusty old OS my VPS uses, I had a really hard time getting it to build, and even once it built it started segfaulting like mad.
Should've gone with something simpler first. Java has built-in libraries for this. It only took a few seconds to adapt this code on Stack Overflow into Clojure code.
(use 'clojure.contrib.java-utils)
(defn make-thumbnail [filename new-filename width]
(let [img (javax.imageio.ImageIO/read (as-file filename))
imgtype (java.awt.image.BufferedImage/TYPE_INT_ARGB)
width (min (.getWidth img) width)
height (* (/ width (.getWidth img)) (.getHeight img))
simg (java.awt.image.BufferedImage. width height imgtype)
g (.createGraphics simg)]
(.drawImage g img 0 0 width height nil)
(.dispose g)
(javax.imageio.ImageIO/write simg "png" (as-file new-filename))))

2 Comments
This post is very old, but the code still works in Clojure 1.3.0, if you omit the clojure.contrib.java-utils, and do this instead:
(import javax.imageio.ImageIO) (import java.awt.image.BufferedImage) (use '[clojure.java.io :only [as-file]])
```clojure (import javax.imageio.ImageIO) (import java.awt.image.BufferedImage) (use '[clojure.java.io :only [as-file]])
```
Speak your Mind
Preview