How to judge whether a file is an image in java:
1. 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 }
This kind of judgment is useful There is a more common method, but this method is very inappropriate. If someone slightly changes the extension of a file that is not a picture to the extension of a picture, it will bypass your verification. If this is uploaded If the file is shell, PHP or jsp, then your website is basically in the hands of others.
2. Determine the file header
If the suffix is unknown or the suffix is 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, Determine by MimetypesFileTypeMap
public class ImageCheck { private MimetypesFileTypeMap mtftp; public ImageCheck(){ mtftp = new MimetypesFileTypeMap(); /* 不添加下面的类型会造成误判 详见:http://stackoverflow.com/questions/4855627/java-mimetypesfiletypemap-always-returning-application-octet-stream-on-android-e*/ 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. Determine by ImageIO (the applicable image format for this method is bmp/gif/jpg/png)
try { // 通过ImageReader来解码这个file并返回一个BufferedImage对象 // 如果找不到合适的ImageReader则会返回null,我们可以认为这不是图片文件 // 或者在解析过程中报错,也返回false Image image = ImageIO.read(file); return image != null; } catch(IOException ex) { return false; }
For more java knowledge, please pay attentionjava Basic tutorial column.
The above is the detailed content of How to determine whether a file is an image in java. For more information, please follow other related articles on the PHP Chinese website!