tags:

views:

1063

answers:

3

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)?

+6  A: 

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.

bcash
pixels is an int[][] of pixels yes?
Ziggy
Nope, my first answer was actually incorrect (sorry). Hopefully the edit will help. Unfortunately the javadoc for this method doesn't do a good job of describing what the array needs to be.
bcash
also! Having trouble with BufferedImage.TYPE_RGB trouble of the "cannot be resolved" variety"...
Ziggy
Corrected in the edit three.
bcash
Oh and what doc are you looking at! I should know that too!
Ziggy
I added the javadoc links to the answer.
bcash
Oh man, I am not getting this at all. So I have this image, and I converted it into an in[][] parts of which I used in the constructors of 52 GImages. But I don't know how to ask an int for it's color? I mean, come on! GImage knows how, but not I.
Ziggy
Create an java.awt.Color with the int using this constructor:http://java.sun.com/javase/6/docs/api/java/awt/Color.html#Color(int)Then use Color.getRed(), Color.getGreen() and Color.getBlue() to construct the int[] for the pixel color.
bcash
A: 

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

Coderer
+1  A: 

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&amp;q=acme+java+gif&amp;btnG=Search

deworde