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.

Comments

51 responses to “Create animated GIF from multiple images in Java”

  1. … [Trackback]

    […] Find More to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  2. … [Trackback]

    […] Read More on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  3. … [Trackback]

    […] Read More here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  4. … [Trackback]

    […] Find More Information here on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  5. … [Trackback]

    […] Information on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  6. … [Trackback]

    […] There you can find 61795 additional Information to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  7. … [Trackback]

    […] Find More to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  8. … [Trackback]

    […] Information on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  9. … [Trackback]

    […] Read More on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  10. … [Trackback]

    […] Read More Information here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  11. … [Trackback]

    […] Find More on on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  12. … [Trackback]

    […] Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  13. … [Trackback]

    […] Find More Information here on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  14. … [Trackback]

    […] Here you can find 16911 more Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  15. … [Trackback]

    […] Here you can find 53289 more Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  16. … [Trackback]

    […] Here you will find 57648 more Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  17. … [Trackback]

    […] There you will find 53243 more Information to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  18. … [Trackback]

    […] Find More here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  19. … [Trackback]

    […] Here you will find 26649 additional Info to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  20. … [Trackback]

    […] Information on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  21. … [Trackback]

    […] Read More on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  22. … [Trackback]

    […] There you can find 48658 additional Info to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  23. … [Trackback]

    […] Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  24. … [Trackback]

    […] There you will find 4666 more Information to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  25. … [Trackback]

    […] Read More on to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  26. … [Trackback]

    […] Find More on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  27. … [Trackback]

    […] Find More Information here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  28. … [Trackback]

    […] Info to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  29. … [Trackback]

    […] There you can find 49804 additional Information to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  30. … [Trackback]

    […] Find More on to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  31. … [Trackback]

    […] Find More here on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  32. … [Trackback]

    […] Read More here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  33. … [Trackback]

    […] Read More on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  34. … [Trackback]

    […] Info on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  35. … [Trackback]

    […] Find More here to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  36. … [Trackback]

    […] Information to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  37. … [Trackback]

    […] Find More to that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  38. … [Trackback]

    […] Read More Information here on that Topic: genuinecoder.com/how-to-create-gif-from-multiple-images-in-java/ […]

  39. sans ordonnance kamagra remede tarif en pharmacie

    acheter kamagra acheter bon marche franche comte

  40. order enclomiphene no prescription online

    purchase enclomiphene generic available in united states

  41. how to buy androxal buy japan

    order androxal price prescription

  42. discount dutasteride price generic

    how to buy dutasteride price at walmart

  43. order flexeril cyclobenzaprine non prescription online

    ordering flexeril cyclobenzaprine buy online australia

  44. get gabapentin using mastercard

    ordering gabapentin purchase prescription

  45. fildena next day

    cheapest buy fildena canada fast shipping

  46. how to buy itraconazole france where to buy

    discount itraconazole coupons

  47. canadian cheap staxyn

    buy cheap staxyn generic prices

  48. canadian avodart pharmacy

    ordering avodart generic available in united states

  49. how to buy rifaximin canada medicine

    rifaximin ups delivery only

  50. buy xifaxan overnight cod

    how to order xifaxan cheap now

  51. kamagra objednテ。vejte online bez ト考enstvテュ pナ册s noc

    výhody nad kamagra

Leave a Reply