Java 如何检查文件是否为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18208359/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:19:45  来源:igfitidea点击:

How to check if the file is an image

javaimageexception

提问by Alaa

I want to check if the file passed is an image and if not I want to show a message indicating that the file is not an image .

我想检查传递的文件是否是图像,如果不是,我想显示一条消息,表明该文件不是图像。

try{
    Image img = ImageIO.read(new File(name));
}catch(IOException ex)
{
    valid=false;
    System.out.println("The file" + name + "could not be opened, it is not an image");
}

When the file (referenced by name) is not an image valid is not set to false, why is this happening? Should I change the type of the exception? I have read about the try-catch, and as I understand if ImageIO.read fails and the type of the exception is IOException contents of catch block will be executed. So why its not executed ?

当文件(由 引用name)不是图像有效未设置为 时false,为什么会发生这种情况?我应该更改异常的类型吗?我已经阅读了 try-catch,据我所知,如果 ImageIO.read 失败并且异常类型是 IOException 将执行 catch 块的内容。那么为什么它没有被执行呢?

Is there is any other way to check if the file is an image??

有没有其他方法可以检查文件是否是图像?

采纳答案by Brent Worden

According to the Javadocs, read returns nullif the file can not be read as an image.

根据Javadocsnull如果无法将文件作为图像读取,则 read 返回。

If no registered ImageReader claims to be able to read the resulting stream, nullis returned.

如果没有注册的 ImageReader 声称能够读取结果流,null则返回。

So, your code should be the following:

因此,您的代码应如下所示:

try {
    Image image = ImageIO.read(new File(name));
    if (image == null) {
        valid = false;
        System.out.println("The file"+name+"could not be opened , it is not an image");
    }
} catch(IOException ex) {
    valid = false;
    System.out.println("The file"+name+"could not be opened , an error occurred.");
}

回答by Hybrid Developer

Use this to get the extension:

使用它来获取扩展名:

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

And check the conditions as u want

并根据需要检查条件

if(extension=="jpg"){
//your code
}

and so on

等等

回答by Evgeniy Dorofeev

According to API ImageIO.read(...)returns nullif no registered ImageReaderable to read the specified file is found, so you can simply test returned result for null.

如果没有注册能够读取指定文件,则根据 APIImageIO.read(...)返回,因此您可以简单地测试.nullImageReadernull