您的位置:首页 > 编程语言 > Java开发

java 根据输入流检查图片格式

2013-01-14 11:55 239 查看
/**
* File extensions.
*/
private static final String[] FILE_EXTS = {"JPG", "PNG", "GIF"};
/**
* Magic bytes in a file with above extension.
*/
private static final byte[][] FILE_MAGS = new byte[][] {
new byte[] {(byte)0xFF, (byte)0xD8, (byte)0xFF, (byte)0xE0}, //JPG

new byte[] {(byte)0x89, (byte)0x50, (byte)0x4E, (byte)0x47}, //PNG
new byte[] {(byte)0x47, (byte)0x49, (byte)0x46, (byte)0x38}  //GIF
};
/**
* Get file format from file name.
* @param fileName file name
* @return file format, null if unsupported.
*/
public static String getFileFormat(String fileName) {
int dp = fileName.lastIndexOf(".");
if (dp == -1) return null;
String ext = fileName.substring(dp + 1).toUpperCase();
if (ext.equals("JPEG")) ext = "JPG"; //JPEG is JPG
if (ArrayUtils.indexOf(FILE_EXTS, ext) == -1) return null;
return ext;
}
/**
* Get file format by contents.
* @param contents file contents
* @return file format, null if unsupported.
*/
public static String getFileFormat(byte[] contents) {
for (int i = 0; i < FILE_MAGS.length; i++) {
byte[] mag = FILE_MAGS[i];
if (contents.length >= mag.length) {
if (Arrays.equals(Arrays.copyOf(contents, mag.length), mag)) {
return FILE_EXTS[i];
}
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: