0

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?

Phil H.
  • 81
  • 3
  • 1
    I don't have an answer but it looks like you're using JPG for the file and then adding it as PNG. Is the code correct? – stdunbar Mar 01 '17 at 19:40
  • I fixed the post, it was supposed to say PICTURE_TYPE_JPEG. But the problem persists. any ideas? – Phil H. Mar 01 '17 at 20:08
  • Is the image ok before it gets put into the document? – stdunbar Mar 01 '17 at 20:19
  • yes. and if I add the uncompressed image instead, it is fine. So the problem seems to be within the compression itself. – Phil H. Mar 01 '17 at 20:40
  • 1
    What file format is the input image? What color model does it use? Does it have an alpha channel? Can you attach an image showing the result with distorted color? PS: If you want the file size to be smaller, using a very high JPEG quality, like `0.98` may not be what you want. Lower values create smaller images, `0.75` is the default. – Harald K Mar 02 '17 at 08:41

1 Answers1

0

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);
Phil H.
  • 81
  • 3