class="java" name="code"> public static final HashMap map = new HashMap();
static {
map.put("89504E47", "png");
map.put("49492A00", "tif");
map.put("FFD8FF", "jpg");
}
public static String getFileType(String filePath) {
return (String) map.get(getFileHeader(filePath));
}
public static String getFileHeader(String filePath) {
FileInputStream is = null;
String value = null;
try {
is = new FileInputStream(filePath);
byte[] b = new byte[4];
/*
* int read() 从此输入流中读取一个数据字节。 int read(byte[] b) 从此输入流中将最多 b.length
* 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
* 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
}
}
}
return value;
}
private static String bytesToHexString(byte[] src) {
StringBuilder builder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
String hv;
for (int i = 0; i < src.length; i++) {
// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
if (hv.length() < 2) {
builder.append(0);
}
builder.append(hv);
}
// System.out.println(builder.toString()+"4");
return builder.toString();
}
/**
* ############################################################################
*/
public static String getImageType(File srcFilePath) {
FileInputStream imgFile;
byte[] b = new byte[10];
int l = -1;
try {
imgFile = new FileInputStream(srcFilePath);
l = imgFile.read(b);
imgFile.close();
} catch (Exception e) {
return null;
}
if (l == 10) {
byte b0 = b[0];
byte b1 = b[1];
byte b2 = b[2];
byte b3 = b[3];
byte b6 = b[6];
byte b7 = b[7];
byte b8 = b[8];
byte b9 = b[9];
for (int i = 0; i < 10; i++) {
System.out.println(b[i]);
}
if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
return "gif";
} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
return "png";
} else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
return "jpg";
} else {
return null;
}
} else {
return null;
}
}
public static void main(String[] args) {
File file = new File("D:/home/ubuntu/BoneAgeDemo/CT/JPG/20171229100855.jpg");
getFileType("D:/home/ubuntu/BoneAgeDemo/CT/JPG/f-d-5-2-20.tif");
getImageType(file);
}
? ??getImageType测了一下tif文件,其中的ASCII码为73 73 42 0 8 0 0 0 13 0,没有验证出来,其次就是读取图片带过来的长与宽,基本就是这样了
? ?