我想检查我从一个目录中读取的文件是否是jpg,但我不想只是检查扩展名.我在想另一种方法是阅读标题.我做了一些研究,我想用
ImageIO.read
Run Code Online (Sandbox Code Playgroud)
我见过这个例子
String directory="/directory";
BufferedImage img = null;
try {
img = ImageIO.read(new File(directory));
} catch (IOException e) {
//it is not a jpg file
}
Run Code Online (Sandbox Code Playgroud)
我不知道从哪里开始,它需要整个目录...但我需要目录中的每个jpg文件.有人可以告诉我我的代码有什么问题或者需要添加什么?
谢谢!
您可以读取缓冲图像中存储的第一个字节.这将为您提供确切的文件类型
Example for GIF it will be
GIF87a or GIF89a
For JPEG
image files begin with FF D8 and end with FF D9
Run Code Online (Sandbox Code Playgroud)
http://en.wikipedia.org/wiki/Magic_number_(programming)
试试这个
Boolean status = isJPEG(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"));
System.out.println("Status: " + status);
private static Boolean isJPEG(File filename) throws Exception {
DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
try {
if (ins.readInt() == 0xffd8ffe0) {
return true;
} else {
return false;
}
} finally {
ins.close();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12412 次 |
| 最近记录: |