import java.awt.*;
import java.awt.image.*;


public class Raster extends Component{
  
  protected int width;
  protected int height;
  protected int pixel[];

  ///////////////////////// CONSTRUCTORS ///////////////////
  
  /**
   *  This constructor, which takes no arguments,
   *  allows for future extension.
   */
  public Raster() {; }
  
  /**
   *  This constructor creates an uninitialized
   *  Raster Object of a given size (w x h).
   */
  public Raster(int w, int h) {
    width = w;
    height = h;
    pixel = new int[w*h];
  }
  
  /**
   *  This constructor creates an Raster initialized
   *  with the contents of an image.
   */
  public Raster(Image img) {
    try {
      PixelGrabber grabber = new PixelGrabber(img, 0, 0, -1, -1, true);
      if (grabber.grabPixels()) {
	width = grabber.getWidth();
	height = grabber.getHeight();
	pixel = (int []) grabber.getPixels();
      }
    } catch (InterruptedException e) {
    }
  }
  
  ////////////////////////// METHODS //////////////////// 
  
  /**
   *  Returns the number of pixels in the Raster
   */
  public final int getsize( ) {
    return pixel.length;
  }
  
  /**
   *  Fills a Raster with a solid color
   */
  public final void fill(Color c) {
    int s = getsize();
    int rgb = c.getRGB();
    for (int i = 0; i < s; i++)
      pixel[i] = rgb;
  }
  
  /**
   *  Converts Rasters to Images
   */
  public final Image toImage(Component root) {
    return root.createImage(new MemoryImageSource(width, height, pixel, 0, width));
  }


  /**
   *  Converts Rasters to Images
   */
  public Image newtoImage()
  {
    return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, pixel, 0, width));
  }
  
  
  /**
   *  Gets a pixel from a Raster
   */
  public final int getPixel(int x, int y) {
    return pixel[y*width+x];
  }
  
  /**
   *  Gets a color from a Raster
   */
  public final Color getColor(int x, int y)  {
    return new Color(pixel[y*width+x]);
  }
  
  /**
   *  Sets a pixel to a given value
   */
  public final void setPixel(int pix, int x, int y) {
    pixel[y*width+x] = pix;
  }
  
  /**
   *  Sets a pixel to a given color
   */
  public final void setColor(Color c, int x, int y) {
    pixel[y*width+x] = c.getRGB();
  }

  public final int getWidth() {
    return width;
  }

 public final int getHeight() {
    return height;
  }

  public final void printPixels() {
    for( int y=0; y< height; y++ ) {
      for( int x=0; x< width; x++ ) {
	System.out.println( (y*width+x) + " pixel[ "+ x +", " + y +"]=" + pixel[y*width+x] );
      }
    }
  }



}//RASTER

