How to determine the file size of an image of arbitrary format (JPEG, PNG, etc.) on the JVM?

I would like to go through the catalog and select all the images, and then do some things based on their sizes. What libraries are available to me for this?

I work in Clojure, but all that is available on the JVM is fair play.

Thanks in advance!

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

You can use with-openit to close the stream automatically.

Here is a usage example for iterating over a number of files in a directory. All files in the directory are assumed to be images. The examples directory only contains a stackoverflow crash.

(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])
+8

javax.io - , .

(import 'java.io.File)
(import 'java.io.FileInputStream)
(import 'javax.imageio.ImageIO)

(def img  (ImageIO/read (FileInputStream. (File. "myfile.png"))))

[ (.getWidth img) (.getHeight img)]
  • png, jpg.
  • . InputStream Clojure.
+3

Perhaps a more effective answer might be

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

(defn dimensions [src]
  (let [res (if (string? src) (io/file (io/resource src)) src)]
    (if res
      (let [image-input-stream (ImageIO/createImageInputStream res)
            readers (ImageIO/getImageReaders image-input-stream)]
        (if-let [r (and (.hasNext readers) (.next readers))]
          (try
            (.setInput r image-input-stream)
            [(.getWidth r 0) (.getHeight r 0)]
            (finally
              (.dispose r)))))
      [0 0])))

It does not require to read the entire image into memory.

Adapted from fooobar.com/questions/96644 / ...

0
source

Source: https://habr.com/ru/post/1775700/


All Articles