resizer / src / resizer / resizer.clj

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

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

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

(defn get-type [img]
  (if (= (.getType img) 0)
    BufferedImage/TYPE_INT_ARGB
    (.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: http://www.mkyong.com/java/how-to-resize-an-image-in-java/"
  [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)
    buff-img))

(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)))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.