/** The CreateGrayscaleImage class creates grayscale images.
    * @version 1.0  18 Feb 2000
    * @author Lawrence Rodrigues
    **/
import java.awt.*;
import java.awt.image.*;
import java.awt.color.*;
import java.util.*;

public class CreateGrayscaleImage {
   short pixels[];
   BufferedImage grayScaleImage;
   int imageWidth =256, imageHeight = 256;
   int imageDepth = 8;
   Object data;
   public CreateGrayscaleImage() { }

   public void setImageDimension(int width, int height) {
      this.imageWidth = width;
      this.imageHeight = height;
   }

   public void setImageDepth(int depth){
      this.imageDepth = depth;
   }

   public void setData(short data[]){
      this.data = data;
   }

   public BufferedImage createImage() {
      ComponentColorModel ccm = new ComponentColorModel(
                          ColorSpace.getInstance(ColorSpace.CS_GRAY),
                          new int[] {imageDepth}, false, false,
                          Transparency.OPAQUE,
                          DataBuffer.TYPE_USHORT);
      ComponentSampleModel csm = new ComponentSampleModel(
                                    DataBuffer.TYPE_USHORT,
                                    imageWidth, imageHeight,1,imageWidth, new int[] {0});
      DataBuffer dataBuf = new DataBufferUShort((short[])data, imageWidth);
      WritableRaster wr = Raster.createWritableRaster(csm, dataBuf, new Point(0,0));
      Hashtable ht = new Hashtable();
      ht.put("owner", "Lawrence Rodrigues");

      return  new BufferedImage(ccm, wr, true, ht);
   }
   public static void  main(String[] args){
      CreateGrayscaleImage gs = new CreateGrayscaleImage();
      int wid = 64, ht =64;
      short data[] = new short[wid*ht];
      for(int i=0; i<ht; i++){
          for(int j=0; j<wid; j++){
              data[i*ht+j] = (short)j;
          }
      }
      gs.setImageDimension(wid,ht);
      gs.setData(data);
      BufferedImage bi = gs.createImage();
      if(bi != null) com.vistech.util.JpegUtil.saveImageAsJPEG(bi, "gr1.jpg");
   }
}
