我正在尝试设计一个报告模板,其中有多个(数百个)图像被超链接引用。我希望文档低于25Mb(出于电子邮件和其他原因),所以我尝试使用以下代码压缩图像:
//I get the input stream
InputStream ins = entity.images.getInputStream(img);
BufferedImage bufImg = ImageIO.read(ins);
//I compress the image
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
ImageOutputStream outputStream = ImageIO.createImageOutputStream(compressed);
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(0.98f);
jpgWriter.setOutput(outputStream);
jpgWriter.write(null, new IIOImage(bufImg, null, null), jpgWriteParam);
jpgWriter.dispose();
byte[] jpegData = compressed.toByteArray();
//I attempt to add the compressed image
imgRun.addPicture(new ByteArrayInputStream(jpegData), Document.PICTURE_TYPE_JPEG,"text", Units.toEMU(newWidth), Units.toEMU(newHeight));
图像写入文档,但颜色失真。就我而言,它们都是红色/橙色。关于是什么导致这个/做什么的任何想法?
答案 0 :(得分:0)
看起来问题是某些图像是.gifs。
无论如何,我首先简单地在压缩之前将所有图像转换为.jpg来解决问题。见下文:
BufferedImage newBufferedImage = new BufferedImage(bufImg.getWidth(),
bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufImg, 0, 0, Color.WHITE, null);