Search code examples
imageclojurejvm

How can I determine the dimensions of an image file of arbitrary format (JPEG, PNG, etc.) on the JVM?


I'd like to go through a directory and pick out all the images and then do some things based on their dimensions. What libraries are available for me to do this?

I'm working in Clojure but anything available on the JVM is fair game.

Thanks in advance!


Solution

  • (with-open [r (java.io.FileInputStream. "test.jpeg")]
      (let [image (javax.imageio.ImageIO/read r)]
        [(.getWidth image) (.getHeight image)]))
    

    You can use with-open to have the stream closed automatically.

    Here is an example of using to iterate through some number of files in a directory. It assumes all the files in the directory are images. The example directory only contains your stackoverflow avatar.

    (defn files-in-dir [dir]
      (filter #(not (.isDirectory %))
              (.listFiles (java.io.File. dir))))
    
    (defn figure-out-height-width
      [files]
      (map (fn [file]
             (with-open [r (java.io.FileInputStream. file)]
               (let [img (javax.imageio.ImageIO/read r)]
                 [file (.getWidth img) (.getHeight img)])))
           files))
    
    user>(figure-out-height-width (files-in-dir "/home/jmccrary/Downloads/pics/"))
    ([#<File /home/jmccrary/Downloads/pics/test.jpeg> 32 32])