Skip to content

Instantly share code, notes, and snippets.

@threepipes
Last active April 22, 2018 11:58
Show Gist options
  • Select an option

  • Save threepipes/19d764e35decad6789722b32b58bb1bd to your computer and use it in GitHub Desktop.

Select an option

Save threepipes/19d764e35decad6789722b32b58bb1bd to your computer and use it in GitHub Desktop.
(主にTopCoderMMで)アニメーションgifを書き出すためのクラス
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GifWriter {
ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();
BufferedImage buffer;
boolean finish = false;
/**
* @param filename gifを書き出すファイルパスを指定
*/
GifWriter(String filename) {
File outfile = new File(filename);
try {
ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
iw.setOutput(ios);
iw.prepareWriteSequence(null);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param buffer paintにて書き込みが行われるBufferedImageを保持
*/
void set(BufferedImage buffer) {
this.buffer = buffer;
}
/**
* 書き込みが行われた画像をgifに追加
*/
void next() {
if(finish) return;
try {
Thread.sleep(20);
iw.writeToSequence(new IIOImage(buffer, null, null), null);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* 書き込み終了
*/
void close() {
if(finish) return;
try {
finish = true;
iw.endWriteSequence();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@threepipes
Copy link
Author

使い方(走り書きなので後で例コード追加などしっかり書き直します)
下はprincessesAndMonstersでの例

  1. なんとかvis.java の適当な所でGifWriter生成しメンバ変数として持つ
  2. paint(repaint?)で生成されたbufferedimageをsetでセット
  3. 各ターンの終わりあたりでnextでそのターンのフレーム追加
  4. 最後にclose

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment