我想使用Java读取文件夹中的所有图像。
什么时候: 我按下Java应用程序中的按钮, 它应该:
如何进行?
我有用于读取图像以及文件夹中所有图像的代码,但是我上面所说的事情如何完成?
欢迎任何建议或帮助!请提供参考链接!
未经测试,因为未在装有JDK的计算机上进行测试,所以请耐心等待,所有内容均按“原样”输入,但应该可以帮助您入门(请耐心等待……)
import java.awt.image.BufferedImage; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import javax.imageio.ImageIO; public class Test { // File representing the folder that you select using a FileChooser static final File dir = new File("PATH_TO_YOUR_DIRECTORY"); // array of supported extensions (use a List if you prefer) static final String[] EXTENSIONS = new String[]{ "gif", "png", "bmp" // and other formats you need }; // filter to identify images based on their extensions static final FilenameFilter IMAGE_FILTER = new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { for (final String ext : EXTENSIONS) { if (name.endsWith("." + ext)) { return (true); } } return (false); } }; public static void main(String[] args) { if (dir.isDirectory()) { // make sure it's a directory for (final File f : dir.listFiles(IMAGE_FILTER)) { BufferedImage img = null; try { img = ImageIO.read(f); // you probably want something more involved here // to display in your UI System.out.println("image: " + f.getName()); System.out.println(" width : " + img.getWidth()); System.out.println(" height: " + img.getHeight()); System.out.println(" size : " + f.length()); } catch (final IOException e) { // handle errors here } } } } }
这相对简单,只使用标准的JDK打包的类:
File
FilenameFilter
BufferedImage
ImageIO
这些Java教程的课程可能对您也有帮助:
FilenameUtils
FileChooser
通过结合以上所有内容,这很容易做到。