项目中有一些图片,在IE里面没法正确显示。Chrome等没问题。经检查,发现这个图片的扩展名是.jpg,但是实际上是个png。。。。。。把文件保存成正确的.png就没问题了。
为了解决这个问题写了段代码检测所有的jpg, png, gif文件内容和扩展名是否一致(检测文件头)
public class PNGJPGTest {
public static void main(String[] argu) throws IOException {
Path start = Paths.get("C:\\dev\\svn\\web\\");
Files.walkFileTree(start, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs)
throws IOException
{
Path fileName = filePath.getFileName();
Path dirPath = filePath.getParent();
// System.out.println(dirPath + " " + fileName);
check(dirPath, fileName);
return FileVisitResult.CONTINUE;
}
});
}
private static void check(Path dirPath, Path fileName) {
String fn = fileName.toString().toLowerCase();
if (fn.endsWith(".jpg") || fn.endsWith(".png") || fn.endsWith(".gif")) {
int[] header = firstBytes(dirPath, fileName);
String ext = getRealExt(header).toLowerCase();
if (!fn.endsWith(ext)) {
System.out.println("ERROR : " + dirPath.toString() + "\\" + fn + ", should be " + ext);
// System.out.println("cp " + dirPath.toString() + "\\" + fn + " " + dirPath.toString() + "\\" + fileName.toFile().getName().substring(0, fileName.toFile().getName().length() - 4) + "." + ext);
}
}
}
private static String getRealExt(int[] header) {
if (header == null) {
return "UNKNOWN";
}
if (header[0] == 0x47 && header[1] == 0x49 && header[2] == 0x46 && header[3] == 0x38) {
return "GIF";
}
if (header[0] == 0xff && header[1] == 0xd8) {
return "JPG";
}
if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4e && header[3] == 0x47 && header[4] == 0x0D) {
return "PNG";
}
return "UNKNOWN";
}
private static int[] firstBytes(Path dirPath, Path fileName) {
String fullName = dirPath.toAbsolutePath().toString() + File.separator + fileName.toString();
RandomAccessFile f = null;
int[] result = new int[5];
try {
f = new RandomAccessFile(fullName, "r");
int b0 = f.readByte() & 0xff;
int b1 = f.readByte() & 0xff;
int b2 = f.readByte() & 0xff;
int b3 = f.readByte() & 0xff;
int b4 = f.readByte() & 0xff;
result[0] = b0;
result[1] = b1;
result[2] = b2;
result[3] = b3;
result[4] = b4;
return result;
} catch (Exception e) {
return null;
} finally {
if (f != null) {
try {
f.close();
} catch (IOException e) {
}
}
}
}