Bart Vangeneugden
Bart Vangeneugden

Reputation: 3446

Resizing images in PDF using iText: incompatible color conversion

I'm trying to reduce the filesize of a few PDF's in Java. I've found a few techniques to do this. But resizing images seems most effective. I followed this piece of code which uses iText.

It works great on a few PDF's (reduction from 4.5MB to 800KB!) but some stayed unaffected.

I altered the code a bit as follows, so it would accept more Stream objects (and hopefully compress more):

PdfReader reader = new PdfReader(original.getPath());
int size = reader.getXrefSize();
for(int i=0;i<size;i++){
    PdfObject object = reader.getPdfObject(i);
    if (object == null || !object.isStream())
        continue;
    PRStream stream = (PRStream)object;
        PdfImageObject image = new PdfImageObject(stream);
        try{
        BufferedImage bi = image.getBufferedImage();
        //more stuff here

And it did! Some PDF's actually got compressed a lot more. However, I got a strange exception at some that didn't change at all:

javax.imageio.IIOException: Incompatible color conversion
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkColorConversion(JPEGImageReader.java:927)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1028)
    at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:984)
    at javax.imageio.ImageIO.read(ImageIO.java:1438)
    at javax.imageio.ImageIO.read(ImageIO.java:1342)
    at com.itextpdf.text.pdf.parser.PdfImageObject.getBufferedImage(PdfImageObject.java:302)
    at com.example.compression.App.main(App.java:56)

(App.java:56 being the line that says image.getBufferedImage();)

Some research discovered, the Stream it was trying to open was a CMYK JPG.

I'm wondering why these wouldn't open, and how I can resize these images anyway. Thanks

Upvotes: 2

Views: 3300

Answers (1)

woliveirajr
woliveirajr

Reputation: 9483

BufferedImage doesn't deal with CMYK nativally (and I'm not sure if Java does in other native components, anyway).

In the fields listed in Java 6 docs, there's no cmyk color model....

You can take a look at this site, someone tells you how to deal with BufferedImage and CMYK colorspace.

Good luck!

Upvotes: 1

Related Questions