(O+P)ut

アウトプット



(O+P)ut

エンジニアのアウトプット

【Java】複数の画像を元にGIF動画を生成するプログラム

スポンサーリンク

JavaでGif作成

Twitterの話題ワードがどのように遷移しているかを可視化する手順を記事にしました。

ただし、記事の中では文字列から一意の座標を生成するところにフォーカスをあてていました。

今回は、Javaを用いて大量のJPEG画像からGIF画像を生成する手法について紹介します。

紹介とあるように、海外の方*1が書いたソースコードが既に公開されています。
http://elliot.kroo.net/software/java/GifSequenceWriter/GifSequenceWriter.java

特別なライブラリも必要なく、コメントもしっかりと記述されているのでとても参考になります。

以下に抜粋しました。

class GifSequenceWriter {
    public GifSequenceWriter(
        ImageOutputStream outputStream,
        int imageType,
        int timeBetweenFramesMS,
        boolean loopContinuously);

    public void writeToSequence(RenderedImage img);
    public void close();
}

public static void main(String[] args) throws Exception {
  if (args.length > 1) {
    // grab the output image type from the first image in the sequence
    BufferedImage firstImage = ImageIO.read(new File(args[0]));

    // create a new BufferedOutputStream with the last argument
    ImageOutputStream output = 
      new FileImageOutputStream(new File(args[args.length - 1]));

    // create a gif sequence with the type of the first image, 1 second
    // between frames, which loops continuously
    GifSequenceWriter writer = 
      new GifSequenceWriter(output, firstImage.getType(), 1, false);

    // write out the first image to our sequence...
    writer.writeToSequence(firstImage);
    for(int i=1; i<args.length-1; i++) {
      BufferedImage nextImage = ImageIO.read(new File(args[i]));
      writer.writeToSequence(nextImage);
    }

    writer.close();
    output.close();
  } else {
    System.out.println(
      "Usage: java GifSequenceWriter [list of gif files] [output file]");
  }
}

ソースコードの中身

ソースコードを見てみると、

ImageOutputStream output = 
new FileImageOutputStream(new File(args[args.length - 1]));

となっています。

つまり、引数argsの末端が出力GIFのパス、それ以外は入力画像のパスという仕組みです。

そこを少し加工します。
引数ではなくプログラムの中でディレクトリ直下の画像のパスを指定して入力ファイルにしています。
dir.listは名前順でソートされた順序で格納される点は注意してください。

String path = "hoge"; //画像が置いてあるディレクトリ
File dir = new File(path);
File[] files = dir.listFiles();
String[] pathlist = new String[files.length];
for (int i = 0; i < files.length; i++) {
 pathlist[i] = files[i].toString();
}

出力ファイルを指定して実行すると、問題なく稼動しました。

チューニングポイントとしては

timeBetweenFramesMS

という変数でフレームの切り替わりの時間を管理しています。

終わりに

画像をGif化するツールはブラウザ版としてネットにもありますが、画像枚数に制限があったり手動で一枚一枚添付していく手間があったりします。
本記事のプログラムではそこの制約なくアニメーションが作成できるので、その点は優位性があります。

以上、ご参考ください。

*1:Elliot Kroo氏作