Search code examples
javaimagetiffjavax.imageio

Java Handling TIF Images


My question is, what how can I successfully load a .tif file into an Image instance in Java?

Let me give some more detail now. I have read a lot of the threads on stackoverflow on how to handle/convert TIF images in Java. I have tried a lot of the stackoverflow suggestions (I say suggestions, because rarely do the people asking come back and say something has worked for them). I am pretty sure I need to use the Java Advanced Imaging (JAI) library, but I don't think I know how to use it. Let me explain the project now:

I am taking screens of frames from a Processing sketch, and encoding them into video using Xuggler. In the sketch I use Processing's save(file filePath) function to save the current frame to a file. I used to have save("img"+i+".jpg"), but the compression that takes place when creating a jpg was slowing down the recording to 9-10fps, so I switched the file extension to see if I could get varying results, and save("img"+i".tif") was the fastest, allowing me to record at about 22-23fps.

Processing can save images as .tif files. Unfortunately though, Java cannot load .tif files back without a library. I used to have the code:
     Image img = Toolkit.getDefaultToolkit().getImage("pics/img"+i+".jpg");
That line of code would load up the .jpg files into img and I'd be good to encode the video. But this line of code (tif instead of jpg):
     Image img = Toolkit.getDefaultToolkit().getImage("pics/img"+i+".tif");
Will not load up any image. I am still able to encode my video with Xuggler, but the images are blank, so I think this method is not working to load my .tif files.

I am working on a Windows 8 computer, and using Eclipse. Any help will be really appreciated!


Solution

  • Yes, you need JAI.

      import javax.media.jai.PlanarImage;
      import com.sun.media.jai.codec.ByteArraySeekableStream;
      import com.sun.media.jai.codec.ImageCodec;
      import com.sun.media.jai.codec.ImageDecoder;
      import com.sun.media.jai.codec.SeekableStream;
      import java.awt.Image;
      import java.awt.image.RenderedImage;
    ...
      static Image load(byte[] data) throws Exception{
        Image image = null;
        SeekableStream stream = new ByteArraySeekableStream(data);
        String[] names = ImageCodec.getDecoderNames(stream);
        ImageDecoder dec = 
          ImageCodec.createImageDecoder(names[0], stream, null);
        RenderedImage im = dec.decodeAsRenderedImage();
        image = PlanarImage.wrapRenderedImage(im).getAsBufferedImage();
        return image;
      }