我想用Java读取文件夹中的所有图像.
时间:我在Java应用程序中按下一个按钮,
它应该:
如何进行?
我有读取图像的代码以及文件夹中的所有图像,但我上面讲的内容是如何完成的?
欢迎任何建议或帮助!请提供参考链接!
hay*_*lem 42
未经测试,因为没有安装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
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样做相对简单,只使用标准的JDK打包类:
Java Tutorial的这些会话也可能对您有所帮助:
FilenameUtils
提取文件的扩展名通过结合以上所有内容,它很容易实现.