How can i get a raw data of image in BufferedImage?
1 posts in topic
Flat View  Flat View

Posted By:   Suchot_Nimitraht
Posted On:   Saturday, December 29, 2001 05:58 AM

Hello all
I have some problem.Please help me about java 2D.
In my project, I use BufferedImage class but i want
to get a raw data of Image.How?
ex. a image 32*24 pixel so i have 768 Pixels,right.
How can i get this raw data of 768 pixels(My Image is 8 bits Grayscale so the raw data range in 0-255)I want this integer(0-255) from 768 pixels
Please help me if you give code to me I will appreciate.
Thank you so much

Little tricky...

Posted By:   Jon_Morton  
Posted On:   Thursday, January 3, 2002 10:48 AM

I wrote a little bit of code to read pixel data for you. The image I used is the jGuru logo on the upper left of this page. I downloaded it and put it in the same directory as the following class. Normally I use packages and such, but for this simple example I crammed everything together in one class. Sorry if it is messy.

Note that this code sample should be tweaked to get alpha levels of images and such -- right now it only works for RGB BufferedImages.

The technique I used is this:

1. Load an image, draw it onto a BufferedImage

2. Get the Raster of the BufferedImage

3. Use a static Raster method to get pixel information.

4. Display the data to the screen.

* @author Jon Morton

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

public class RasterTool {

Raster raster;
BufferedImage image;

/** Creates new RasterTool */
public RasterTool(int x, int y) {
// Loading an image relative in the same directory as this file.
StringBuffer path = new StringBuffer(getClass().getResource("jguru.gif").getPath());
// Using my own utility to load the image.
Image jguru = loadImages(path.toString());
// Creating a new BufferedImage to pick apart.
image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
// Drawing the image into the buffer.
image.getGraphics().drawImage(jguru, 0, 0, new Panel() );
// Adding image data into a raster.
raster = image.getData();
// Call the function that gets pixel info.
pixelInfo(x, y);

public void pixelInfo(int x, int y) {
System.out.println(" Data: " + raster.getNumDataElements() );
System.out.println(" Bands: " + raster.getNumBands() );
System.out.println("Height: " + raster.getHeight() );
int[] pixel = new int[3];
raster.getPixel(x, y, pixel);
System.out.println(" Red: "+ pixel[0] );
System.out.println(" Green: "+ pixel[1] );
System.out.println(" Blue: "+ pixel[2] );

public static void main(String[] args) {
RasterTool t = new RasterTool(10,10);

// This is a function from one of my libraries that I use to load images.
public static Image loadImages(String path) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
MediaTracker tracker = new MediaTracker(new Panel());
Image image = toolkit.getImage( path );
try {
tracker.addImage( image, 0 );
} catch(InterruptedException ie) {
return image;

About | Sitemap | Contact