我想使用Java读取文件夹中的所有图像。
何时:我按下Java应用程序中的按钮,
它应该:
如何进行?
我有读取图像的代码以及文件夹中的所有图像,但我上面说的内容是如何完成的?
欢迎任何建议或帮助!请提供参考链接!
答案 0 :(得分:42)
未经测试,因为没有安装JDK的计算机,所以请耐心等待所有输入“按原样”,但应该让你开始(预计会有大量的downvotes ......)
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打包类:
Java Tutorial的这些会话也可能对您有所帮助:
FilenameUtils
提取文件的扩展名FileChooser
以选择文件夹。通过结合以上所有内容,这很容易做到。
答案 1 :(得分:1)
javaxt.io.Directory directory = new javaxt.io.Directory(" C:\ Users \ Public \ Pictures \ Sample Pictures"); directory.getFiles(); javaxt.io.File [] files;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
答案 2 :(得分:-1)
step 1=first of all make a folder out of webapps
step2= write code to uploading a image in ur folder
step3=write a code to display a image in ur respective jsp,html,jframe what u want
this is folder=(images)
reading image for folder'
Image image = null;
try {
File sourceimage = new File("D:\\images\\slide4.jpg");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
}