Create animated GIF from multiple images in Java

Java GIF Tutorial

In this tutorial, we will learn how to programmatically create animated GIF by combining multiple images in java easily. We will make use of the library gifencoder for this purpose.

Add the ‘gifencoder’ library to your project

If you are using Gradle, add the following dependency into your build.gradle file.

// https://mvnrepository.com/artifact/com.squareup/gifencoder
implementation group: 'com.squareup', name: 'gifencoder', version: '0.10.1'

If you are using the maven, add the following entry into your pom.xml file.

<!-- https://mvnrepository.com/artifact/com.squareup/gifencoder -->
<dependency>
    <groupId>com.squareup</groupId>
    <artifactId>gifencoder</artifactId>
    <version>0.10.1</version>
</dependency>

If you are using Java 9+ with modules, add the following line into your module-info.java file.

requires com.squareup.gifencoder;

Build GIF from multiple image files

First, let’s build our GIF from 4 image files. The steps for preparing the GIF from images as follows.

  1. Convert the BufferedImages to int[][] pixel array
  2. Provide the image pixel array into the encoder
  3. Encode all the pixel array-based images into GIF image
import com.squareup.gifencoder.FloydSteinbergDitherer;
import com.squareup.gifencoder.GifEncoder;
import com.squareup.gifencoder.ImageOptions;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;

public class JavaGifTutorial {

  public static void main(String[] args) throws Exception {
    JavaGifTutorial gifTutorial = new JavaGifTutorial();
    gifTutorial.createAnimatedGif();
  }

  private void createAnimatedGif() throws Exception {
    File image1 = new File("gifencoder/image1.jpg");
    File image2 = new File("gifencoder/image2.jpg");
    File image3 = new File("gifencoder/image3.jpg");
    File image4 = new File("gifencoder/image4.jpg");

    //The GIF image will be created with file name "my_animated_image.gif"
    try (FileOutputStream outputStream = new FileOutputStream("my_animated_image.gif")) {
      ImageOptions options = new ImageOptions();

      //Set 500ms between each frame
      options.setDelay(500, TimeUnit.MILLISECONDS);
      //Use Floyd Steinberg dithering as it yields the best quality
      options.setDitherer(FloydSteinbergDitherer.INSTANCE);

      //Create GIF encoder with same dimension as of the source images
      new GifEncoder(outputStream, 500, 313, 0)
          .addImage(convertImageToArray(image1), options)
          .addImage(convertImageToArray(image2), options)
          .addImage(convertImageToArray(image3), options)
          .addImage(convertImageToArray(image4), options)
          .finishEncoding(); //Start the encoding
    }
  }

  /**
   * Convert BufferedImage into RGB pixel array
   */
  public int[][] convertImageToArray(File file) throws IOException {
    BufferedImage bufferedImage = ImageIO.read(file);
    int[][] rgbArray = new int[bufferedImage.getHeight()][bufferedImage.getWidth()];
    for (int i = 0; i < bufferedImage.getHeight(); i++) {
      for (int j = 0; j < bufferedImage.getWidth(); j++) {
        rgbArray[i][j] = bufferedImage.getRGB(j, i);
      }
    }
    return rgbArray;
  }
}

GIF created using Java

Create GIF from all the images from a folder

Now, let’s see how we can improve the above code to take all the image files from a folder and use it to make an animated GIF. This way, you can simply put all the images you want to include the GIF image and run the code, no need to mention the individual images separately.

To achieve this, we need to add code for filtering only image files from a directory.

How to take only image files from a directory in Java?

Let’s see how to filter-out only JPEG and PNG files from a directory in Java. We will write code to iterate through all the files present in a directory, and then filter out only the image files by their extension.

private List<File> getAllImageFilesFromFolder(File directory) {
  //Get all the files from the folder
  File[] allFiles = directory.listFiles();
  if (allFiles == null || allFiles.length == 0) {
    throw new RuntimeException("No files present in the directory: " + directory.getAbsolutePath());
  }

  //Filter out only image files
  List<File> acceptedImages = new ArrayList<>();
  for (File file : allFiles) {
    String fileExtension = file.getName().substring(file.getName().lastIndexOf(".") + 1);
    if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("png")) {
      acceptedImages.add(file);
    }
  }

  //Return the filtered images
  return acceptedImages;
}

Create GIF from all the images in the folder

Now, let’s make use of the above function to get all the images from a folder and encode it into a GIF image.

//Trimmed code. Functions and imports used on the first section is excluded to keep the code compact

private void createAnimatedGifFromFolder(String path) throws Exception {
  //The GIF image will be created with file name "gif_from_folder.gif"
  try (FileOutputStream outputStream = new FileOutputStream("my_animated_image.gif")) {
    //Create GIF encoder with same dimension as of the source images
    GifEncoder encoder = new GifEncoder(outputStream, 1920, 1200, 0);

    //Get all the image files
    List<File> imageFiles = getAllImageFilesFromFolder(new File(path));

    //Make sure that at least one image is present
    if (imageFiles.isEmpty()) {
      throw new RuntimeException("No image files present!");
    }

    //Add all the images to the GifEncoder
    ImageOptions options = new ImageOptions();
    for (File imageFile : imageFiles) {
      encoder.addImage(convertImageToArray(imageFile), options);
    }

    //Finish encoding and create the file
    encoder.finishEncoding();
  }
}

private List<File> getAllImageFilesFromFolder(File directory) {
  File[] allFiles = directory.listFiles();
  List<File> acceptedImages = new ArrayList<>();
  for (File file : allFiles) {
    String fileExtension = file.getName().substring(file.getName().lastIndexOf(".") + 1);
    if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("png")) {
      acceptedImages.add(file);
    }
  }
  return acceptedImages;
}

That’s all. The function createAnimatedGifFromFolder(String folder) will go through all the JPG and PNG images available inside it and then use it to make the GIF animated image.

Conclusion

In this tutorial, we have learned how to create an animated GIF image a set of images in Java. Java GIF creation is done with the help of the gifencoder library. If you have liked this article, you might want to check out some of the other articles I have written.

Muhammed Afsal Villan
Muhammed Afsal Villan is an experienced full-stack developer, specialized in desktop and mobile application development. He also regularly publishes quality tutorials on his YouTube channel named 'Genuine Coder'. He likes to contribute to open-source projects and is always enthusiastic about new technologies.

21 COMMENTS