2013-05-09 33 views
2

我是clojure新手(我不知道任何Java可以說)。在沒有臨時磁盤文件的情況下調整clojure中的圖像

我的目標是從URL中獲取圖像並製作縮略圖。我到目前爲止:

(ns myapp.image 
    (:require [clojure.java.io :as io]) 
    (:import [javax.imageio.ImageIO] 
      [java.awt.image.BufferedImage])) 

(defn get-remote-image 
    [url file] 
    (with-open [in (io/input-stream url) out (io/output-stream file)] 
    (io/copy in out))) 

(defn resize 
    "Resize a file. Pass in a width and height." 
    [file-in file-out width height] 
    (let [img  (javax.imageio.ImageIO/read (io/file file-in)) 
     imgtype (java.awt.image.BufferedImage/TYPE_INT_ARGB) 
     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" (io/file file-out)))) 

現在它從URL抓取圖像並將其寫入磁盤,緩衝區緩衝區。然後它從磁盤讀取數據並將其大小調整到內存中,再次將其寫入新文件。最後,我可以刪除第一個副本。

我想一次性完成整個操作,沒有臨時磁盤寫入。我並不特別在意記憶中的整個形象......對於我的目的而言,它們一般都是小圖像。

我不明白如何將數據從io流傳遞到java.awt.image.BufferedImage對象。

回答

2

使用read方法ImageIO需要URL作爲參數並返回BufferedImage對象。

5

我剛剛創建了一個新的libray Imagez,你可能會發現有用:它有一個scale-image功能應該做的正是你想做的事,縮放圖像方面:

(use 'mikera.image.core) 

;; scale an image into a thumbnail of a given size 
(def thumbnail (scale-image some-buffered-image new-width new-height)) 

這可能是一個好主意,讓圖像處理操作與IO功能分開,因此如果需要(例如進行測試),您可以在內存中執行與文件系統依賴關係的所有操作。

相關問題