I am attempting to write some Java code that takes an image from a source file and saves it as a GIF file using a custom palette that I have generated. I’ve found that the easiest way to do this so far is to use the MemoryImageSource class, but I’m not sure of the best method of saving the data to a file after it is set up. Some sample source might clarify what I am trying to do:
BufferedImage image = ImageIO.read(new File(sourceImageFilename));
IndexColorModel palette = getCustomGeneratedPalette();
byte[] imageIndiciesIntoPalette = getPixelIndiciesIntoPalette(image, palette);
MemoryImageSource finalImage = new MemoryImageSource(image.getWidth(),
image.getHeight(),palette, imageIndiciesIntoPalette, 0, image.getWidth());
// cast exception on next line
ImageIO.write((RenderedImage) finalImage, "gif", new File(targetImageFileName));
All I want to do is save the image to a gif using the custom palette I have created – any suggestions that do not use some 3rd party library would be greatly appreciated.
I found a solution, mostly borrowed from:
(Do not open this website, it is now unsafe/infected.)
http://www.exampledepot.com/egs/java.awt.image/Mandelbrot2.htmlIt does not use MemoryImageSource, but rather constructs a BufferedImage with the custom
palette and a raster that is created from a SampleModel.