Can't read and write a TIFF image file using Java ImageIO standard library

I don't know what to do with TIFF images, but I can't read or write any of them using straight Java standard ImageIO library. Any thoughts?

Thanks.


Solution 1:

If you don't like or can't use JAI for any reason I have written a TIFF ImageReader plugin for ImageIO, available on GitHub. It is pure Java and does not need any native installs, and comes with a very friendly open source license (BSD).

It supports any baseline TIFF option, along with a lot of standard extensions. From version 3.1 the TIFF plugin also has write support.

With the proper JARs in your class path, usage can be as simple as:

BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);

Solution 2:

According to JEP 262: TIFF Image I/O the TIFF plugin that used to be part of JAI will be available as part of the Java SE, starting from Java 9.

That means, using Java 9 or later, the following code will just work, without any extra imports or dependencies:

BufferedImage image = ImageIO.read(inputTIFF);
// ...modify image (compose, resize, sharpen, etc)...
ImageIO.write(image, "TIFF", outputTIFF);

I haven't yet been able to verify the support for non-baseline TIFF flavors in this plugin, but I assume at least baseline TIFFs should be fully supported.

Solution 3:

I tried JAI, and it didn't work for me.

Where are you stuck? Does the following work for you?

import java.io.File;
import java.io.FileOutputStream;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;

public class Main {
    public static void main(String args[]) {
        File file = new File("input.tif");
        try {
            SeekableStream s = new FileSeekableStream(file);
            TIFFDecodeParam param = null;
            ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
            RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(0),
                                               null,
                                               OpImage.OP_IO_BOUND,
                                               null);
            FileOutputStream fos = new FileOutputStream("output.jpg");
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
            jpeg.encode(op.getData());
            fos.close();
        }
        catch (java.io.IOException ioe) {
            System.out.println(ioe);
        } 
    }
}