
import java.awt.*;
import java.awt.image.*;

// An instance is an image map: an internal version of a picture. See
// the constructor to see how an image is "grabbed" and stored for
// manipulation.
public class ImageMap {
    
    Image image; // The image
    int rows;    // number of rows in image
    int cols;    // number of columns in image
    int[] map;   // the pixel map
    
    // = the number of rows
    public int getRows() {
        return rows;
    }
    
    // = the number of columns
    public int getCols() {
        return cols;
    }
    
    // = map
    public int[] getMap() {
        return map;
    }
    
    // Set number of rows to r
    public void setRows(int r) {
        rows= r;
    }
    
    // Set number of columns to c
    public void setCols(int c) {
        cols= c;
    }
    
    // Constructor: A map from image v with r rows and c cols.
    // A variable of class Image contains a .jpeg or .gif image.
    // Class PixelGrabber is given an image, as well as the number
    // of rows and cols it should contain, and an int array map into
    // which this image should be stored. Calling method grabPixels
    // then causes the image to be stored in one-dimensional
    // array map --even though a picture is a two-dimensional thing.
    // The two-dimensional array of elements is stored in map in
    // row-major order.
    public ImageMap(Image i, int r, int c) {
        image= i;
        rows= r;
        cols= c;
        map= new int[rows*cols];
        if (image == null) return;
        PixelGrabber pg = new PixelGrabber(image,0,0,cols,rows,map,0,cols);
        try {
            pg.grabPixels();
        }
        catch (InterruptedException e) {
            System.out.println("pixel grab interrupted!");
            return;
        } 
    }
    
    // = a copy of this
    public ImageMap copy() {
        return new ImageMap(image,rows,cols);
    }
    
    // = the pixel value in the image map at [row,col]
    public int getPixel(int row, int col) {
        return map[row*cols + col];
    }
    
    // set the pixel value in the image map at [row,col] to pixValue
    public void setPixel(int row, int col, int pixValue) {
        map[row*cols + col]= pixValue;
    }
    
    // swap the pixel at [a,b] with the pixel at [i,j]
    public void swapPixels(int a, int b, int i, int j) {
        int temp= getPixel(a,b);   // temporary pixel
        setPixel(a,b,getPixel(i,j));
        setPixel(i,j,temp);
    }
}

