加载并显示文件夹中的所有图像
我想用Java读取文件夹中的所有图像。
时间:我按下Java应用程序中的按钮,
这应该:
- 在弹出窗口中询问目录的路径,
- 然后从该目录加载所有图像,
- 然后显示他们的名字,尺寸类型和尺寸。
如何进行?
我有用于读取图像的代码以及文件夹中的所有图像,但我上面讲的内容是如何完成的?
欢迎任何建议或帮助! 请提供参考链接!
未经测试,因为没有安装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 } } } } }
使用的API
这样做比较简单,只使用标准的JDK打包类:
-
File
-
FilenameFilter
-
BufferedImage
-
ImageIO
Java Tutorial的这些会话也可以帮助您:
- 读取/加载图像
- 如何使用图标
- 如何使用文件选择器
可能的增强
- 使用Apache Commons
FilenameUtils
提取文件的扩展名 - 根据实际的mime类型或内容检测文件,而不是基于扩展名
- 我将UI代码留给您。 由于我不知道这是否是家庭作业,我不想提供完整的解决方案。 但要继续:
- 查看
FileChooser
以选择文件夹。 - 我假设你已经知道如何制作帧/窗口/对话框。
- 阅读Java教程 如何使用图标部分,它们教您如何显示和标记它们。
- 查看
- 我遗漏了一些需要处理的问题:
- exception处理
- 带有邪恶束缚的文件夹(假设你有一个文件夹“TryMeIAmEvil.png”)
通过结合以上所有内容,它很容易实现。
javaxt.io.Directory directory = new javaxt.io.Directory(“C:\ Users \ Public \ Pictures \ Sample Pictures”); directory.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(); } }