Qoppa’s 100% Java PDF optimizer library, jPDFOptimizer, allows, among other things, to change the properties of images in a PDF document including the compression, the color space, and the DPI resolution.
This is done using the ImageHandler interface and implementing the convertImage() method which allows an application to define optimization option per image or per image type.
public class MyImageOptimizer implements ImageHandler { // this is the method where you can implement any image conversion / optimization public ImageOutput convertImage(ImageInfo imageInfo) { // construct an image output that by default retains the same image properties as the image input ImageOutput imageoutput = new ImageOutput(ImageOutput.CO_BW, CO_JBIG2); // for gray or black and white images, use JBIG2 compressions if(imageInfo.isGray() || imageInfo.isMonochrome()) { imageoutput.setCompression(ImageOutput.CO_JBIG2); imageoutput.setColorSpace(ImageOutput.CS_BW); } // for color images, use JPEG 2000 compression if(imageInfo.isColor()) { imageoutput.setCompression(ImageOutput.CO_JPEG2000); imageoutput.setCompressionQuality(0.8f); } // downgrade image resolution to 200DPI if it's higher if (imageInfo.getDPIX() > 200 || imageInfo.getDPIY() > 200) { // Calculate new dimensions to match DPI float scale = Math.min(200 / imageInfo.getDPIX(), 200 / imageInfo.getDPIY()); int newWidth = (int)(imageInfo.getImageWidth() * scale + 0.5); int newHeight = (int)(imageInfo.getImageHeight() * scale + 0.5); imageoutput.setImageWidth(newWidth); imageoutput.setImageHeight(newHeight); } // return the new image output return imageoutput; } |
The imageHandler is set through the OptSettings class.
// Create the PDF Optimizer object with the path of the file to optimize pdfOptimizer = new PDFOptimizer("C:\myfile.pdf", null); // Set optimization settings OptSettings options = new OptSettings(); // ... set standard optimization settings ... // set the image handler options.setImageHandler(new MyImageHandler()); // run the optimizer and save pdfOptimizer.optimize(options, "C:\myfile_opt.pdf"); |
Method | Options |
Image Compression
ImageOutput.setCompression() |
Retain existing compression or convert any image to either a JPEG, JPEG2000, FLATE, or JBIG2.
|
Compression Quality
ImageOutput.setCompressionQuality() |
Allows the compression quality to be adjusted between 0.1 and 1 (corresponding to a quality from 10 to 100%).
|
Image Color Space ImageOutput.setColorSpace() |
Choose to either retain or convert the image colors to Grayscale or B&W.
*Note – When the retain option is selected CMYK images will be converted to RGB due to a regression bug in Java 1.7. |
DPI ResolutionImageOutput.setImageWidth() ImageOutput.setImageHeight() |
Adjust the image resolution by changing the imageWidth and imageHeight in pixels. The image bounds will stay the same when displayed on the page. |