Search code examples
javajakarta-eeimage-processingjai

JAI ClassNotFound Exception when calling JAI.create


I am trying to read a .tif image using javax.media.jai.JAI. Here is my code:

import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

BufferedImage image = null;
if(extension.toLowerCase().equals("tif")) {
    RenderedOp op = JAI.create(fileName, file);
    image = op.getAsBufferedImage();
} else {
    image = ImageIO.read(file);
}

The "file" (Java.io.File) and "fileName" (String) parameters are fine. But when it gets to the "JAI.create(...)" line, I get this exception:

java.lang.ClassNotFoundException: javax.media.jai.JAI

I'm not sure why it can't find JAI. Any ideas?


Solution

  • JAI doesn't come with the JDK. You get it separately. Find the appropriate JAR library here. Then add that to your path.

    Note: If you are using Windows, you can get the jar and specify the path by yourself. Or get the exe which will install the same jar and add it to your system classpath. I would prefer to set the paths by myself.

    On Ubuntu, you can also install it via

    sudo apt-get install libjai-core-java
    

    Loading Image can be done like this:

    public BufferedImage loadImage(String filePath){
        RenderedOp img = JAI.create("fileload", filePath);
        return img.getAsBufferedImage();
    }
    

    "fileload", as a literal String, is the name of the operation to load an image from a file using JAI.create(). That could also throw an exception if fileName is not equal to "fileload".