How to convert TIFF to JPEG/PNG in java

Had gone through some study and testing, found a method to convert TIFF to JPEG and sorry for pending so long only uploaded this answer.

SeekableStream s = new FileSeekableStream(inFile);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = dec.decodeAsRenderedImage(0);

FileOutputStream fos = new FileOutputStream(otPath);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
fos.flush();
fos.close();

otPath is the path that you would like to store your JPEG image.
For example: “C:/image/abc.JPG”;
inFile is the input file which is the TIFF file

At least this method is workable to me. If there is any other better method, kindly share along with us.

EDIT: Just want to point out an editing in order to handle multipage tiff. Obviously you also have to handle the different names for the resulting images:

for (int page = 0; page < dec.getNumPages(); page++) { 
    RenderedImage op = dec.decodeAsRenderedImage(page );
    ...
}

Leave a Comment