如何确定JVM上任意格式(JPEG,PNG等)的图像文件的尺寸? [英] How can I determine the dimensions of an image file of arbitrary format (JPEG, PNG, etc.) on the JVM?

查看:70
本文介绍了如何确定JVM上任意格式(JPEG,PNG等)的图像文件的尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想浏览目录并挑选出所有图像,然后根据它们的尺寸进行一些操作.我可以使用哪些库来做到这一点?

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?

我正在Clojure中工作,但是JVM上可用的任何东西都是公平的游戏.

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

提前谢谢!

推荐答案

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

您可以使用with-open自动关闭流.

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

这里是一个用于遍历目录中一定数量文件的示例.假定目录中的所有文件均为图像.示例目录仅包含您的stackoverflow头像.

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

这篇关于如何确定JVM上任意格式(JPEG,PNG等)的图像文件的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆