Source

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]]
        [resizer.cfenv :as cf])
  (: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! (cf/mongo-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 [filename]
  (. (read-file filename) getInputStream))

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

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

(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 resize-image [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))

;; fetches image from gridfs
;; resizes image
;; stores new image into gridfs with the small_ prefix
(defn process-image [filename]
  (let [original-image (image-from-input-stream filename)
        resized-image (resize-image original-image width height)]
    (save-file (buffimg-to-bytearray resized-image) filename {:format "jpg"} "image/jpg")))
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.