converting tiff to jpeg - the java way
yes I thought it should be easy, at least typical.
but I was not able to find a clean and easy way to do so.
I started looking into javax.imageio,
realizing that it only support basic formats like gif, jpeg, bmp.
Anything beyond that will need custom plugin.
I searched through forums and heard of stuffs called JAI -
the Java Advanced Imaging library,
however i couldnt find the plugin I needed for tiff.
Screwed up for two hours I finally found out that there is a separate package called JAI-imageio,
which is not included in JAI. Yea…..what a great confusion.
Once I got that all the rest is straight forward.
public static void convertToJpg(String path) throws IOException {
ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
ImageInputStream iis = ImageIO.createImageInputStream(new File(path));
reader.setInput(iis, false);
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
String filename = path.substring(path.lastIndexOf("\\")+1, path.lastIndexOf("."));
for (int i=0; i<reader.getNumImages(true); i++) {
BufferedImage image = reader.read(i);
String outputFileName = filename+"_"+(i+1)+".jpg";
ImageOutputStream ios = ImageIO.createImageOutputStream(new File(outputFileName));
writer.setOutput(ios);
writer.write(image); // (*)
}
}
If you need to have control over the output quality,
you will have to add these line:
ImageWriteParam writeParams = (ImageWriteParam) writer.getDefaultWriteParam(); writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // value ranged from 0.0 to 1.0 for minimum file size, worst quality to maximum file size, best quality writeParams.setCompressionQuality(0);
and replace the line marked by (*) with :
writer.write(null, new IIOImage(image, null, null), writeParams);
Concerning performance,
it costs about 28s to convert a 7-page tiff (383kb in file size) with dimension 5100 x 6122,
to 7 jpeg files with the same dimension (4.27mb totally(!), with highest compression).
Changing the compression ratio seems to have very little effect on the time.
All other type of conversion can be done in similar way,
as long as you’ve got the required plugin.
Comments(0)


