Site iconJava PDF Blog

How to view Multi-TIFF files in Java

How to view Multi-TIFF files in Java

In this article, I will show you how to read and view Multi-TIFF files in Java. We already have an article on How to read TIFF images in Java, why not check it out!

What is a Multi-TIFF file?

TIFF (Tag Image File Format) files are able to contain multiple images. This is what we would call a Multi-TIFF file.

How to view in Java?

First you need to read the images into Java. The standard JDK does not support multi-tiff images so you will need to use an additional library such as JDeli. You can only store one image in a BufferedImage, so JDeli returns an image count and a method to read each image.

final TiffDecoder tiff = new TiffDecoder();
final int imageCount = tiff.getImageCount(file);
BufferedImage image = tiff.readImageAt(currentIm, file);

Once you have the images as BufferedImages, they are easy to display in Java.

If you have read my previous post on How to view images in Java, then you already have an image viewer in Java or you can clone our Java Image Viewer github repository. You can now modify it to view multi-TIFF images.

Additional code needed to support Multi-Tiff files in Java Viewer

First, you  need to read each image in the file and display it. You can achieve this by keeping a count of the images in the file:
final TiffDecoder tiff = new TiffDecoder();
final int imageCount = tiff.getImageCount(file);

Then displaying them one by one with buttons to allow you to cycle through them, much like in our JDeli viewer.

final int currentIm = 0;
final JButton next = new JButton("Next image");
final JButton prev = new JButton("Previous image");
next.addActionListener(a -> {
if (currentIm < imageCount - 1) {
currentIm++;
drawImage();
}})
prev.addActionListener(a -> {
if (currIm > 0) {
curentIm--;
drawImage();
}})
// Add the buttons to the viewer
final JPanel multiButtons = new JPanel();
multiButtons.add(prev);
multiButtons.add(next);
add(multiButtons, BorderLayout.PAGE_END);

The draw image method would be one you’d use to set the image each time something like:

void drawImage() {
BufferedImage image = tiff.readImageAt(currentIm, file);
imageLabel.setIcon(new ImageIcon(image));
}

Now you can view all the images in your multi-TIFF file!