Java处理图片错误

0

下午没事看了看服务器的错误日志,全是两个错误,你来一个我来一个循环往复,这里记录一下。

javax.imageio.IIOException: I/O error reading PNG header!
	at com.sun.imageio.plugins.png.PNGImageReader.readHeader(PNGImageReader.java:315)
	at com.sun.imageio.plugins.png.PNGImageReader.readMetadata(PNGImageReader.java:654)
	at com.sun.imageio.plugins.png.PNGImageReader.readImage(PNGImageReader.java:1229)
	at com.sun.imageio.plugins.png.PNGImageReader.read(PNGImageReader.java:1577)

javax.imageio.IIOException: Not a JPEG file: starts with 0x89 0x50
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(JPEGImageReader.java:604)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(JPEGImageReader.java:342)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(JPEGImageReader.java:476)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(JPEGImageReader.java:597)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1054)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1034)

这两个错误原因很简单:就是你把PNG格式的图片保存为JPG后缀或者把JPG格式的图片保存为PNG后缀,也就是用户的图片后缀是错误的,需要自己去获取正确的图片格式。

有时PS打开也会提示:无法完成请求,因为文件格式模块不能解析该文件。

读取图片

FileInputStream is = new FileInputStream("d://test.jpg");;
ImageInputStream iis = null;
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(is);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(0, 0, 100, 100);
param.setSourceRegion(rect);
BufferedImage image = reader.read(0, param);
ImageIO.write(image, "jpg", new File("d://test_.jpg"));

这里的图片就是PNG的,就是单纯改了一下后缀,这里就会出现问题。
其实只需要修改ImageIO.getImageReadersByFormatName这个方法的文件后缀名正确就可以了,后面write这里的参数是没有问题的。

获取图片正确格式

private static final String JPG_HEX = "ff";
private static final String PNG_HEX = "89";
private static final String JPG_EXT = "jpg";
private static final String PNG_EXT = "png";

public static String getFileExt(String filePath) {
	FileInputStream fis = null;
	String extension = FilenameUtils.getExtension(filePath);
	try {
		fis = new FileInputStream(new File(filePath));
		byte[] bs = new byte[1];
		fis.read(bs);
		String type = Integer.toHexString(bs[0]&0xFF);
		if(JPG_HEX.equals(type)) {
			extension = JPG_EXT;
		}
		if(PNG_HEX.equals(type)) {
			extension = PNG_EXT;
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if(fis != null) {
				fis.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return extension;
}

参考文章:http://www.2cto.com/kf/201207/140517.html

类似还有一个异常:Not a JPEG file: starts with 0x47 0x49,这个是因为GIF图片后缀改成了JPG