Image Representation in Java
1. Load Image:
import java.applet.*; // image will display on Java applet
import java.awt.image.*; //deal with image object
import java.awt.*; //deal with Graphic Interface
// Image "ass1.jpg" should be placed in "images" subdirectory
// getCodeBase() return a URL for the applet
Image image=getImage(getCodeBase(),"images/ass1.jpg");
MediaTracker tracker = new MediaTracker(this);
// Register it with media tracker
tracker.addImage(image, 0);// id=0-- identifier used to track this image.
// Wait until image has loaded
try {
tracker.waitForID(0);
} catch (InterruptedException e){}
2. Get image information after the image is fully loaded:
int imageWidth=image.getWidth(this);
int imageHeight=image.getHeight(this);
int[] pixels = new int[imageWidth*imageHeight];
// grab pixels
PixelGrabber pg = new PixelGrabber(image, 0, 0, imageWidth, imageHeight, pixels, 0, imageWidth);
try {
pg.grabPixels();
} catch(InterruptedException e) {}
3. draw the image at (0,0):
public void paint(Graphics g) {
//draw the image at (0,0)
g.drawImage(image, 0, 0, this);
}
4. pixel representation of an color image in Java:
int red = (pixels[i]>> 16) & 0xff;
int green = (pixels[i]>> 8) & 0xff;
int blue = (pixels[i]) & 0xff;
5. create Image with given pixels[]:
Image image = createImage(new MemoryImageSource(imageWidth, imageHeight, pixels, 0, imageWidth));// offset=0