resizer / src / resizer / resizer.clj

(ns resizer.resizer
  (:require [clojure.string :as cs]
            [monger.core :as mg]
            [monger.gridfs :as gfs])
  (:use [monger.gridfs :only [store-file make-input-file filename content-type metadata]]
        [claude.core :as cf])
  (:import [java.awt.image BufferedImage]
           [ ByteArrayOutputStream]
           [javax.imageio ImageIO]))

(defonce height 225)
(defonce width 225)
(defonce default-url "mongodb://")

(defn mongo-connect []
  (if (cf/cloudfoundry?)
    (mg/connect-via-uri! (cf/mongo-url))
    (mg/connect-via-uri! default-url)))

(defn get-type [img]
  (if (= (.getType img) 0)
    (.getType img)))

(defn read-file [filename]
  (gfs/find-one {:filename filename}))

(defn file-input-stream [file]
  (. file getInputStream))

(defn image-from-input-stream [filename]
  (. ImageIO read (file-input-stream (read-file filename))))

(defn buffimg-to-bytearray [img format]
  (with-open [baos  (ByteArrayOutputStream.)]
    (ImageIO/write img format baos)
    (.flush baos)
    (.toByteArray baos)))

(defn resize-image
  "Resizes image: based on this blog post:"
  [original-image w h]
  (let [buff-img (BufferedImage. w h (get-type original-image))
        g (.createGraphics buff-img)]
    (.drawImage g original-image 0 0 w h nil)
    (.dispose g)

(defn save-file [file-buffer fname fmetadata fctype]
  (store-file (make-input-file file-buffer)
              (filename (cs/join ["small_" fname]))
              (metadata fmetadata)
              (content-type fctype)))
(defn get-format [mime]
  (last (.split mime "/")))

(defn process-image
  "- Fetches image from gridfs and converts it to an ImageIO
   - Resizes the image.
   - Stores new image into gridfs with the small_ prefix"
  [filename mime]
  (let [original-image (image-from-input-stream filename)
        resized-image (resize-image original-image width height)
        img-byte-array (buffimg-to-bytearray resized-image (get-format mime))]
    (save-file img-byte-array filename {:format (get-format mime)} mime)))