Replace this:
BufferedImage img = new BufferedImage(w * n, h, BufferedImage.TYPE_INT_RGB);
with
BufferedImage img = new BufferedImage(w * n, h, BufferedImage.TYPE_INT_ARGB);
...and you'll have transparency.
Possibly better yet, is to do:
BufferedImage img = reader.getRawImageType(0).createBufferedImage(w * n, h);
Then you'll keep the exact image layout from the GIF, and possibly get a smaller output image (a minor detail here, is that getRawImageType
may return null
if there's no corresponding color space in Java, but this should probably never happen for a GIF).
Unrelated to the issue, but still good practice: Whenever you do img.createGraphics()
you should also call dispose()
on the Graphics2D
when done painting. Move the createGraphics()
outside the loop and dispose
after the loop for better performance.
It's even possible to avoid the drawing altogether, and read the contents of each frame directly into img
, by replacing your loop with something like this:
ImageReadParam param = reader.getDefaultReadParam();
param.setDestination(img);
for (int i = 0; i++; i < n) {
param.setDestinationOffset(new Point(w * i, 0);
reader.read(i, param);
}