javaapache-poibufferedimagexwpfbufferedoutputstream

Images in apache POI XWPF document have color distortion


I am attempting to design a report template which has many(hundreds of) images being referred to by hyperlinks. I want the document to be under 25Mb (for email and other reasons), so I'm trying to compress the images using the following code:

//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));

The images write to the document, but their color is distorted. In my case they are all red/orange in color. Any ideas as to what is causing this/what to do?


Solution

  • it looks like the problem was that some of the images were .gifs.

    regardless, I solved the problem by first simply converting all the images to .jpg before compression. See below:

    BufferedImage newBufferedImage = new BufferedImage(bufImg.getWidth(),
              bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
    newBufferedImage.createGraphics().drawImage(bufImg, 0, 0, Color.WHITE, null);