Java - Generate BlurHash Examples

Wolt BlurHash is an algorithm for generating a placeholder representation for an image. It can be used to generate the blurred version of an image, which is much smaller than the original file, so it can be loaded first before the real image completely loaded. If you're developing a Java application and you need to generated BlurHash for your images, this tutorial shows you how to do it.

There are two important libraries we are going to use. The first one is io.trbl.blurhash library.

pom.xml

  <dependency>
      <groupId>io.trbl</groupId>
      <artifactId>blurhash</artifactId>
      <version>1.0.0</version>
  </dependency>

build.gradle

  compile group: 'io.trbl', name: 'blurhash', version: '1.0.0'

The second one is javax.imageio for reading the image and generate BufferedImage which is needed by the blurhash library. It's a built-in Java library, so you don't need to update your dependency.

Code Examples

To generate a blurhash, simply use BlurHash.encode. It requires a parameter of type BufferedImage, here are some ways to do it.

Generate from Local File

If the file is stored on local storage, you can create a File object of that image and convert it to BufferedImage.

  try {
      BufferedImage image = ImageIO.read(new File("/path/to/file.avif"));

      String blurHash = BlurHash.encode(image);
  } catch (IOException e) {
      e.printStackTrace();
  }

Generate from URL

If you have the URL of the file and you don't want to donwload it, you can pass a URL instance instead of a File instance. ImageIo.read has bult-in support for BMP, GIF, JPEG, PNG, and WBMP. There are also plugins for other formats such as JPEG 2000 and TIFF.

  try {
      BufferedImage image = ImageIO.read(new URL("http://example.com/image.avif"));

      String blurHash = BlurHash.encode(image);
  } catch (IOException e) {
      e.printStackTrace();
  }