package com.mindprod.example;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.IndexColorModel;
import java.io.File;
import java.io.IOException;
/**
* Demonstrate the use of IndexColorModel with a map of possible colours.
* <p/>
* Directly generate a png file with a palette limited to 256 colours.
* Draws three nested rectangles, lawn green, tomato, transparent,
* but what you get is two nested rectangles, lawn green and hot pink.
* Such images are 1/4 the size of images encoded with 32-bit colours.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.1 2011-01-11 add comments
* @since 2006-03-02
*/
public class TestIndexColorModel
{
/**
* height of image in pixels
*/
private static final int height = 50;
/**
* width of image in pixels
*/
private static final int width = 50;
private static final Color LAWN_GREEN = new Color( 0x7c, 0xfc, 0x00 );
private static final Color TOMATO = new Color( 0xff, 0x63, 0x47 );
private static final Color TRANSPARENT = new Color( 0, 0, 0, 0 );
/**
* map of encoding to full colour
*/
private static final int[] colourMap
= {
0x00000000,
0xff000000,
0xffffffff,
0xffff0000,
0xffffff00,
0xff00ff00,
0xff0000ff,
0xff00ffff,
0xffff00ff,
0xff7cfc00,
0xffff69b4,
0xffff1493,
0xffffb6c1,
};
/**
* Create an IndexColorModel Image and write it to disk.
*
* @param args not used
*
* @throws java.io.IOException if problem writing png file.
*/
public static void main( String args[] ) throws IOException
{
IndexColorModel colorModel = new IndexColorModel( 8
,
colourMap.length,
colourMap,
0
,
true
,
0
,
DataBuffer.TYPE_BYTE );
BufferedImage image = new BufferedImage( width, height,
BufferedImage.TYPE_BYTE_INDEXED, colorModel );
Graphics2D g = image.createGraphics();
g.setBackground( LAWN_GREEN );
g.clearRect( 0, 0, width, height );
g.setColor( TOMATO );
g.fillRect( 10, 10, width - 20, height - 20 );
g.setColor( TRANSPARENT );
g.fillRect( 20, 20, width - 40, height - 40 );
ImageIO.write( image, "PNG", new File( "C:/temp/indexcolormodelexample.png" ) );
}
}