In this blog post, I will show you how to read WebP files in Java. We also have a related article covering how to write WebP files in Java.
ImageIO does not support WebP file types by default so you will need to use an ImageIO plugin or an external library. I will demonstrate using an Open source ImageIO plugin and using the JDeli Image Library.
What is WebP?
WebP is a relatively new file format for bitmap images created by Google to work on web browsers. WebP images are designed to be small and therefore fast to load, using both lossy and lossless compression.
You can read more about the WebP image format in our previous article.
The filename extension for WebP files is:
How to read a WebP image in Java with ImageIO
Step 1 Download an ImageIO plugin (try this one or this one) and add it to classpath.
Step 2 Create a File handle, InputStream, or URL pointing to the raw WebP image.
Step 3 ImageIO will now be able to read a WebP file into a BufferedImage. This syntax is like so:
BufferedImage image = ImageIO.read(webpfFileOrInputStreamOrURL)
How to read a WebP image in Java with JDeli
Step 1 Add JDeli to your class or module path. (download the trial jar).
Step 2 Create a File handle, InputStream pointing to the raw WebP image. You can also use a byte containing the image data.
Step 3 Read the WebP image into a BufferedImage
BufferedImage image = JDeli.read(webpFile);
Why use JDeli to read WebP images?
JDeli offers a range of advantages over ImageIO and alternatives, including:
- Prevent heap related JVM crashes from ImageIO use of native memory
- Improve read performance
- Support for threading
- Support for later versions of Java and Java modules
Read and write images in Java with one line of code
Read an Image with
BufferedImage image = JDeli.read(streamOrFile);
and write an Image with
JDeli.write(myBufferedImage, OutputFormat.HEIC, outputStreamOrFile)