Read Tiff format in Java eclipse

2020-08-09 04:09发布

问题:

How do i read a TIFF image using Java IMAGEIO library??(I am using Eclipse Luna)..And once i download the plugin(JAR files) how to give the Classpath so that it can read my input TIFF image file?

回答1:

Here a quick example to convert a TIFF image into a PNG image.

// quick conversion example
File inputFile = new File("image.tiff");
File outputFile = new File("output.png");
BufferedImage image = ImageIO.read(inputFile);
ImageIO.write(image, "png", outputFile);

Print a list of all supported formats of the JAI ImageIO library.

import javax.imageio.ImageIO;
...
for (String format : ImageIO.getWriterFormatNames()) {
    System.out.println("format = " + format);
}

note For the convertion of image formats which have no built-in support a supporting library must be in the classpath. To find the supported formats check https://docs.oracle.com/javase/tutorial/2d/images/loadimage.html or the snippet above.

e.g. for TIFF you could use the jai_imageio-1.1.jar (or newer).

javac -cp jai_imageio-1.1.jar:. Main.java
java -cp jai_imageio-1.1.jar:. Main

If no TIFF format supporting library is in the classpath the above convertion snippet fails with java.lang.IllegalArgumentException: image == null!.

Following formats have built-in support (Java 8)

BMP
GIF
JPEG
PNG
WBMP

jai_imageio-1.1.jar adds support for

JPEG2000
PNM
RAW
TIFF

edit As times goes by and Java 9 is released, a small update, because Java 9 supports TIFF now out of the box.

compile and run with Java 9 without an additional library

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
class TiffToPng {
    public static void main(String[] args) throws Exception {
        File inputFile = new File("image.tiff");
        File outputFile = new File("output.png");
        BufferedImage image = ImageIO.read(inputFile);
        ImageIO.write(image, "png", outputFile);
    }
}

to find supported ImageReader / ImageWriter formats resp. MIME types you could use following snippets

for (String format : ImageIO.getReaderFormatNames()) {
    System.out.println("format = " + format);
}
...
for (String format : ImageIO.getReaderMIMETypes()) {
    System.out.println("format = " + format);
}


for (String format : ImageIO.getWriterFormatNames()) {
    System.out.println("format = " + format);
}
...
for (String format : ImageIO.getWriterMIMETypes()) {
    System.out.println("format = " + format);
}


回答2:

If you are getting the error:

java.lang.IllegalArgumentException: image == null!

Just put the below jar :-

  • If you are using eclipse, just add it to referenced libraries.
  • If you are using just simple java file and running it through console, just paste this jar in the class path.

jai_imageio-1.1.jar | http://www.java2s.com/Code/JarDownload/jai/jai_imageio-1.1.jar.zip

And Import the following :

import com.sun.media.imageio.plugins.tiff.*;


标签: java tiff