To judge whether a file is a picture, it is not comprehensive to judge only by the suffix name. If the suffix of a txt file is changed to gif, it will be regarded as a picture, and java can judge whether the file itself is a picture, which can prevent the Trojan horse virus disguised as a picture. When uploading images, limit the upload file size to prevent impact on server availability.
package com.tx.img;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class IsImageFile {
public static void main(String[] args) throws IOException {
File file=new File("D:\\java_work\\img\\Firefox.png");
System.out.println(isImageFile(file));
}
public static boolean isImageFile(File file) {
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file); // resFile is to be
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {// The file is not a picture
System.out.println("This file is not a picture file");
return false;
}
iis.close();
} catch (IOException e) {
e.printStackTrace ();
}
return true;
}
}