java 检查文件是否为有效的 jpg
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15539696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if file is a valid jpg
提问by Teddy13
I would like to check if the file I am reading in from a directory is a jpg but I do not want to simply check the extension. I am thinking an alternative is to read the header. I have done some research and I want to use
我想检查我从目录中读取的文件是否为 jpg,但我不想简单地检查扩展名。我在想另一种方法是阅读标题。我做了一些研究,我想使用
ImageIO.read
I have seen the example
我看过例子
String directory="/directory";
BufferedImage img = null;
try {
img = ImageIO.read(new File(directory));
} catch (IOException e) {
//it is not a jpg file
}
I am not sure where to go from here, it takes in the entire directory... but I need each jpg file in the directory. Can someone tell me what is wrong with my code or what additions need to be made?
我不知道从哪里开始,它需要整个目录......但我需要目录中的每个 jpg 文件。有人可以告诉我我的代码有什么问题或需要添加哪些内容吗?
Thank you!
谢谢!
采纳答案by karthick
You can read the first bytes stored in the buffered image. This will give you the exact file type
您可以读取存储在缓冲图像中的第一个字节。这将为您提供确切的文件类型
Example for GIF it will be
GIF87a or GIF89a
For JPEG
image files begin with FF D8 and end with FF D9
http://en.wikipedia.org/wiki/Magic_number_(programming)
http://en.wikipedia.org/wiki/Magic_number_(编程)
Try this
试试这个
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();
}
}
回答by MadProgrammer
You will need to get the readers used to read the format and check that there are no readers available for the given file...
您需要让阅读器用于阅读格式并检查给定文件是否没有可用的阅读器...
String fileName = "Your image file to be read";
ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName ));
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
boolean canRead = false;
while (readers.hasNext()) {
try {
ImageReader reader = readers.next();
reader.setInput(iis);
reader.read(0);
canRead = true;
break;
} catch (IOException exp) {
}
}
Now basically, if none of the readers can read the file, then it's not a Jpeg
现在基本上,如果没有读者可以读取文件,那么它就不是 Jpeg
Caveat
警告
This will only work if there are readers available for the given file format. It might still be a Jpeg, but no readers are available for the given format...
这仅在给定文件格式有可用的阅读器时才有效。它可能仍然是 Jpeg,但没有读者可用于给定的格式......