Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize an image in clojure without a temporary disk file

I'm a clojure newbie (and I don't know any Java to speak of).

My goal is to take an image from a URL and make a thumbnail of it. I've got this so far:

(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))))

Right now it grabs the image from the url and writes it to disk, buffer to buffer. Then it reads from the disk and resizes the image in memory, writing it again to the new file. Finally, I can delete the first copy.

I'd like to do the whole operation in a single pass, without the interim disk writes. I don't particularly mind having the whole image in memory... for my purposes, they will generally be smallish images.

I don't understand how to pass the data from the io stream to a java.awt.image.BufferedImage object.

like image 668
Sir Robert Avatar asked May 13 '26 18:05

Sir Robert


1 Answers

I just created a new libray Imagez that you may find useful: it has a scale-image function that should do exactly what you want in terms of scaling the 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))

It's probably a good idea to keep the image processing operations separate from the IO functions so that you can do everything in-memory withot filesystem dependencies if you need to (e.g. for testing).

like image 163
mikera Avatar answered May 19 '26 03:05

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!