Java makes it very easy to create images as BufferedImages which can then be saved out in standard image file formats. Here is the code to save an image as a Tif image using the JAI image (a free library from Sun).
com.sun.media.jai.codec.TIFFEncodeParam params = new com.sun.media.jai.codec.TIFFEncodeParam();
FileOutputStream os = new FileOutputStream(outputDir + imageName+”.tif”);
javax.media.jai.JAI.create(“encode”, image, os, “TIFF”, params);
This works very nicely but there are a number of extra tricks worth knowing.
Firstly, there is a compression option available to compress the image – use the modified code as shown below. There are several types of compression but several of them produce Tif files which will not display under Windows or Mac – COMPRESSION_PACKBITS works well.
com.sun.media.jai.codec.TIFFEncodeParam params = new com.sun.media.jai.codec.TIFFEncodeParam();
params.setCompression(com.sun.media.jai.codec.TIFFEncodeParam.COMPRESSION_PACKBITS);
Secondly, the type of image you save out can have a huge effect on the size of the Tif image. If you save a grayscale image, it produces a much smaller file and also compresses much better than an RGB or ARGB image. You can find out the image type by using image.getType() – the int values returned are all static Constants in the BufferedImage class.
You can convert the image to another format by creating a second BufferedImage in that format and drawing the original image onto it. Here is the code to make any image grayscale.
BufferedImage image_to_save2=new BufferedImage(image_to_save.getWidth(),image_to_save.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
image_to_save2.getGraphics().drawImage(image_to_save,0,0,null);
image_to_save = image_to_save2;
For our PDF library, we always generate images in ARGB (we need to because PDF files can have transparency which only works in ARGB). But sometimes the image is only grayscale. Using both these tricks of converting to grayscale and compressing allowed us to reduce the size of the Tif files created from a sample PDF file from 1.4 Meg to 52K – pretty impressive!
Why use JDeli?
JDeli is the IDR solutions Image library which makes writing Tif files much faster and simpler. It offers a range of advantages over ImageIO and alternatives, including:
- prevents heap related JVM crashes
- implements unsupported image formats
- reduce output file size
- improve read/write performance
- supports threading
- superior image scaling algorithms
Why not check out this tutorial on Reading and Writing TIFF files in Java with JDeli
Do you need to solve any of these problems in Java?
Convert PDF to HTML5 | Convert PDF to SVG | View Forms in the browser |
View PDF Documents | Convert PDF to image | Extract Text from PDF |
Read/Write images | Replace ImageIO | Convert Image to PDF |