Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.


Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Thumbs from Downloaded Images in Clojure

The code creates a thumb from either a local file or a remote URI. It combines ideas from a blog post dealing with image downoads in clojure and an older post dealing with thumbnail creation.

(import javax.imageio.ImageIO)
(import java.awt.image.BufferedImage)
(use '[clojure.java.io :only [as-file input-stream output-stream] :as io])

(defn make-thumbnail-generic [input new-filename width]
  (let [img (javax.imageio.ImageIO/read input)
        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" new-filename)))

(defn make-thumbnail-from-file [filename new-filename width]
  (make-thumbnail-generic filename new-filename width))

(defn make-thumbnail-from-stream [uri file width]
  (with-open [in (io/input-stream uri)
              out (io/output-stream file)]
    (make-thumbnail-generic in out width)))

Example usage:

 (make-thumbnail-from-stream some-image-url (str "~/my_thumbs/"
 (some-image-id) ".png") 100)