Home  >  Article  >  Java  >  Java determines whether it is a picture

Java determines whether it is a picture

尚
Original
2019-11-19 16:07:343612browse

Java determines whether it is a picture

Java method to determine whether it is a picture:

1. Determine whether it is a picture by judging the file suffix name

String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}
//...
if("jpg".equals(extension)){
    //your code
}

2. Determine whether it is a picture by judging the file header.

If the suffix is ​​unknown or the suffix has been modified, the file header can still be used to determine what file type the file is. We can use a text editing tool such as UltraEdit to open the file (in hexadecimal mode), and then see what characters are in the file header. The following are the file header characters for common image types (hexadecimal)

JPEG (jpg),文件头:FFD8FF 
PNG (png),文件头:89504E47 
GIF (gif),文件头:47494638 
TIFF (tif),文件头:49492A00 
Windows Bitmap (bmp),文件头:424D

3. Judge by MimetypesFileTypeMap

public class ImageCheck {
    private  MimetypesFileTypeMap mtftp;

    public ImageCheck(){
        mtftp = new MimetypesFileTypeMap();
        /* 不添加下面的类型会造成误判 
        mtftp.addMimeTypes("image png tif jpg jpeg bmp");
    }
    public  boolean isImage(File file){
        String mimetype= mtftp.getContentType(file);
        String type = mimetype.split("/")[0];
        return type.equals("image");
    }

}

4. Judge by ImageIO

try {
    // 通过ImageReader来解码这个file并返回一个BufferedImage对象
    // 如果找不到合适的ImageReader则会返回null,我们可以认为这不是图片文件
    // 或者在解析过程中报错,也返回false
    Image image = ImageIO.read(file);
    return image != null;
} catch(IOException ex) {
    return false;
}

Note: The applicable image format for this method is bmp/gif/jpg /png

For more java knowledge, please pay attention to java basic tutorial.

The above is the detailed content of Java determines whether it is a picture. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn