In this article I will show you how to write JPEG2000 images in Java. We also have a related article covering how to read JPEG2000 files in Java.
ImageIO is able to write images as JPEG2000 files (jp2 format only), but it offers very little control over the process or the output. We added JPEG2000 support to our JDeli Image library so we could get quality JPEG2000 output. In this article, we show you how to use either JDeli or ImageIO and cover the benefits of JDeli.
What is JPEG2000?
JPEG2000 was developed in 1997-2000 as a replacement for the original JPEG file format. It is not backward compatible. The aim was to produce smaller files than possible with JPEG format. It also uses lossy or lossless compression for digital images.
The file name extensions for JPEG2000 files are: .jp2
and .jpx
.
JPEG versus JPEG2000
Here are the reasons you might want to use JPEG or JPEG2000 image file format.
JPEG
- Optimum file size for small images
- Most widely supported in browsers
- Good color range
- Good for color photos but not that great for plain text
- Low compression ratio for lossy compression
JPEG 2000
- Better on large images (for smaller images jpeg is still smaller)
- No universal browser support
- Encoding is CPU intensive and encoding is not as fast and easy as encoding in jpeg
- The file format is less likely to be affected by ‘bit errors’ and other file system errors due to its more efficient coding structure
How to write an image as a JPEG2000 file in ImageIO
Step 1 ImageIO will need the JAI_ImageIO plugin installed.
Step 2 Create a File (or OutputStream) object for the JPEG2000 output.
File file = new File("/path/to/outputFile.jp2"));
Step 3 Pass image, jpg type and File (or OutputStream) object into write method
ImageIO.write(bufferedImage, "jpeg 2000", file);
How to write an image as a JPEG2000 file with JDeli
Step 1 Add JDeli to your class or module path. (download link to the trial jar).
Step 2 Create a File (or OutputStream) object
File file = new File("/path/to/outputFile.jp2"));
Step 3 Pass image, JPEG2000 type and File (or OutputStream) object into write method
JDeli.write(bufferedImage, "jp2", file);
In JDeli you can also use a typesafe version
JDeli.write(bufferedImage, OutputFormat.JPEG2000, file);
or pass in a Jpeg2000EncoderOptions object for more control over JPEG2000 image output such as level of Compression.
Jpeg2000EncoderOptions options = new Jpeg2000EncoderOptions();
JDeli.write(bufferedImage, options, file);
Start reading and writing images with one line of code
Read: BufferedImage image = JDeli.read(streamOrFile);
Write: JDeli.write(myBufferedImage, OutputFormat.HEIC, outputStreamOrFile)