javax.imageio.IIOException: Not a JPEG file: starts with 0x47 0x49

java处理图片时出现异常

javax.imageio.IIOException: Not a JPEG file: starts with 0x47 0x49
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.getWidth(Unknown Source)
at com.test.filedownloader.ImageHandler.getImageDim(ImageHandler.java:60)
at com.test.filedownloader.ImageHandler.main(ImageHandler.java:96)
Exception in thread "main" java.lang.NullPointerException
at com.test.filedownloader.ImageHandler.getImageDim(ImageHandler.java:70)
at com.test.filedownloader.ImageHandler.main(ImageHandler.java:96)

出现这种错误是因为将gif 图片后缀改成了jpg

解决办法:

根据文件的前面几个字节,判断文件类型

	private String getFileSuffix(final String path) throws IOException {
		String result = "";
		String hex="";
		if (path != null) {
			File image=new File(path);
			InputStream is = new FileInputStream(image);
			byte[] bt = new byte[2];  
			is.read(bt); 
			MyLog.logger.info(bt+"\n"+bytesToHexString(bt));  
			hex=bytesToHexString(bt);
			is.close();
			if(hex.equals("ffd8")){
				result="jpg";
			}else if(hex.equals("4749")){
				result="gif";
			}else if(hex.equals("8950")){
				result="png";
			}
		}
		
		return result;
	}


	public static String bytesToHexString(byte[] src) {  
        StringBuilder stringBuilder = new StringBuilder();  
        if (src == null || src.length <= 0) {  
            return null;  
        }  
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2) {  
                stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString();  
    }

调用的话就

String suffix = getFileSuffix(path);

一个png文件十六进制内容

javax.imageio.IIOException: Not a JPEG file: starts with 0x47 0x49_第1张图片


可参看链接

http://www.acgist.com/article/134.html

http://blog.csdn.net/fenglibing/article/details/7728275

http://www.cnblogs.com/Wendy_Yu/archive/2011/12/27/2303118.html

你可能感兴趣的:(java)