Ziggy
Ziggy

Reputation: 22365

Writing a GIF file in Java

So I have this GIF file on my desktop (it's a 52 card deck of poker cards). I have been working on a program that cuts it up into little acm.graphics.GImages of each card. Now, however, I want to write those GImages or pixel arrays to a file so that I can use them later. I thought it would be as straight forward as writing .txt files, but a couple of Google searches later I am more confused than before.

So how do I go about making .gif files out of pixel arrays or GImages (I've got loads of both)?

Upvotes: 1

Views: 8901

Answers (3)

deworde
deworde

Reputation: 2789

I had to create GIF's out of Java Images for a university project, and I found this. I would recommend Acme's Open-Source GifEncoder Class. Nice and easy to use, I still remember it over 2 years later. Here's the link: http://www.acme.com/java/software/Acme.JPM.Encoders.GifEncoder.html

And here's the G-Link: http://www.google.com/search?hl=en&q=acme+java+gif&btnG=Search

Upvotes: 1

Coderer
Coderer

Reputation: 27264

It doesn't really answer your question directly, but wouldn't it be easier to use ImageMagick? It has Java bindings.

Upvotes: -1

Brendan Cashman
Brendan Cashman

Reputation: 4928

Something along these lines should do the trick (modify the image type, dimensions and pixel array as appropriate):

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

WritableRaster raster = image.getRaster();
for ( i=0; i<width; i++ ) {
    for (  j=0; j<height; j++ ) {
        int[] colorArray = getColorForPixel(pixels[i][j]);
        raster.setPixel(i, j, colorArray);
    }
}

ImageIO.write(image, "gif", new File("CardImage"));

'getColorForPixel' will need to return an array representing the color for this pixel. In this case, using RGB, the colorArray will have three integers [red][green][blue].

Relevant javadoc: WritableRaster, BufferedImage and ImageIO.

Upvotes: 7

Related Questions