Java 读取/缩小图片:javax.imageio.IIOException: Unsupported Image Type
Posted tomcat and jerry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 读取/缩小图片:javax.imageio.IIOException: Unsupported Image Type相关的知识,希望对你有一定的参考价值。
用Java来对图片进行操作:放大/缩小,resize,文件压缩
正常情况下,使用
BufferedImage image = ImageIO.read(new File("d:/test.jpg"));
或者直接使用第三方组件:net.coobird.thumbnailator
net.coobird.thumbnailator.Thumbnails .of(new File("d:/test.jpg")) .size(100,100)//比如原来像素是300x300,现在转成100x100 .toFile(new File("d:/test_100x100.jpg"));
//实际底层也是ImageIO.read(new File("d:/test.jpg"));
有时候遇到图片读取就GG了
javax.imageio.IIOException: Unsupported Image Type at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1079) at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1050) at javax.imageio.ImageIO.read(ImageIO.java:1448) at javax.imageio.ImageIO.read(ImageIO.java:1308)
在stackoverflow上找到了解决方案:
/**
* @author: https://www.cnblogs.com/tomcatandjerry/
* @date 2020-2-26
*/
private static BufferedImage readImageWithNoError(File imageFile) { try { return ImageIO.read(imageFile); } catch (Exception e) { try { //Find a suitable ImageReader Iterator readers = ImageIO.getImageReadersByFormatName("JPEG"); ImageReader reader = null; while (readers.hasNext()) { reader = (ImageReader) readers.next(); if (reader.canReadRaster()) { break; } } //Stream the image file (the original CMYK image) ImageInputStream input; input = ImageIO.createImageInputStream(imageFile); if (input == null) { logger.error("ImageIO.createImageInputStream return null"); return null; } reader.setInput(input); //Read the image raster Raster raster = reader.readRaster(0, null); //Create a new RGB image BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); //Fill the new image with the old raster bi.getRaster().setRect(raster); BufferedImage greyImage = makeGrey(bi); return greyImage; } catch (Exception e1) { logger.error("readImageWithNoError: error", e1); return null; } } } //对图片做灰化处理 public static BufferedImage makeGrey(BufferedImage img) { //更换图片图层: https://www.cnblogs.com/tomcatandjerry/ BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR); bufferedImage.getGraphics().drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null); bufferedImage = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, bufferedImage); return bufferedImage; }
这样就可以正常操作图片了。
>! 注意: 如果是ImageIO.read()出错的文件,转换后,如果按jpg/或者其他方式生成图片,大小跟源文件不同的。如果需要按文件大小来缩放,需要生成一个临时的jpg文件File,用这个File来计算源文件的大小
以上是关于Java 读取/缩小图片:javax.imageio.IIOException: Unsupported Image Type的主要内容,如果未能解决你的问题,请参考以下文章