import static org.apache.commons.codec.binary.Hex.encodeHexString;
import static org.apache.commons.io.FileUtils.openInputStream;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.apache.commons.io.IOUtils.toByteArray;
public static String getFileHeader(File f) {
if (f.length() == 0) {
return null;
} else {
byte[] b = new byte[8];
InputStream in = null;
try {
in = openInputStream(f);
b = toByteArray(in, 8);
} catch (IOException e) {
return "";
} finally {
closeQuietly(in);
}
return encodeHexString(b);
}
}
public static boolean isImage(File image) {
if (image == null) {
return false;
}
String fileHeader = getFileHeader(image);
if (fileHeader == null || fileHeader.isEmpty()) {
return false;
}
fileHeader = fileHeader.toUpperCase();
if (fileHeader.equals("89504E470D0A1A0A")) { // PNG
return true;
} else if (fileHeader.matches("^FFD8.*")) { // JPG
return true;
} else if (fileHeader.matches("^474946383961.*") || fileHeader.matches("^474946383761.*")) { // GIF
return true;
} else if (fileHeader.matches("^424D.*")) { // BMP
return true;
}
return false;
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme