我想使用 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 打包类:
Java 教程的这些会话也可能对您有所帮助:
FilenameUtils
提取文件的扩展名通过结合以上所有内容,这很容易做到。
javaxt.io.Directory 目录 = new javaxt.io.Directory("C:\Users\Public\Pictures\Sample Pictures"); 目录.getFiles(); javaxt.io.File[] 文件;
java.io.FileFilter filter = file -> !file.isHidden() && (file.isDirectory() || (file.getName().endsWith(".jpg")));
files = directory.getFiles(filter, true);
System.out.println(Arrays.toString(files));
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();
}
}