/*
  DataToImage.java
  Demonstrates how to render data as an image on the screen.
*/
import java.io.*;
import java.awt.Frame;
import java.awt.image.*;
import java.awt.image.ColorModel;
import java.awt.color.ColorSpace;
import java.awt.*;

import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.*;

public class DataToImage {
 
  public static void main(String[] args) throws InterruptedException {
    
    int width = 128;     //image width
    int height = 192;    //image height
    
    //create a SampleModel object
    SampleModel  samplemodel = new BandedSampleModel ( DataBuffer.TYPE_BYTE, width, height, 3 );
    //use sRGB as our color space
    ColorSpace colorspace = ColorSpace.getInstance ( ColorSpace.CS_sRGB );
    
    //create a color model using our color space (sRGB), each color component is 8-bit,
    // no alpha, no alpha premultiplied, opaque, data type is BYTE
    int[] bits = { 8, 8, 8 };
    ColorModel  colormodel = new ComponentColorModel( colorspace, bits, false, false,
	Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); 

    //allocate array to hold RGB data
    int samples []  = new int[3*width*height];      
    
    //create a TiledImage using the sample model and color model defined above
    TiledImage outImage; 
    outImage = new TiledImage( 0, 0, width, height, 0, 0, samplemodel, colormodel );
    
    int isize = width * height;    //image size
    int bands = 3;                 //3 bands: Red, Green, Blue
    int k = 0;

    //create some artificial sample data for rendering
    for ( int i  = 0; i < isize; i++, k+=3 ){   
        samples[k] = 255;          //red
      if ( i < isize / 2 ) {       //first half red
        samples[k+1] = 0;          //green
        samples[k+2] = 0;          //blue
      } else {                     //second half white
        samples[k+1] = 255;        //green
        samples[k+2] = 255;        //blue
      }
    }
    //assign data to the image
    k = 0;
    for (int y = 0; y < height; y++) 
      for (int x = 0; x < width; x++) 
        for (int band=0; band < bands; band++) 
          outImage.setSample(x, y, band, samples[k++] );

    /* Attach image to a scrolling panel to be displayed. */
    ScrollingImagePanel panel = new ScrollingImagePanel( outImage, width, height );

    /* Create a frame to contain the panel. */
    Frame window = new Frame("Red and White");
    window.add(panel);
    window.pack();
    window.show();
    Thread.sleep( 10000 ); //sleep for ten seconds
    window.dispose();      //close the frame
  }
}

