Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can I read a pixel color 1

Status
Not open for further replies.

modalman

Programmer
Feb 14, 2001
156
GB
Hi. I have an image within an applet and I need to know what color the mouse has clicked on. Can I read the color of the pixel at a given coordinate. Many thanks in advance.
 
you can certainly get a component's, or its context, colorusing Graphics abstract class. But as for pixels not too sure. Let me know if you find out though as it would be handy to know.
 
I think you'll have an Image object that contains the data anyway (for buffering purposes, as the image data will be lost when it's hidden somehow - it will not be redrawn if you did not buffer it). I suggest using a BufferedImage for that.

The BufferedImage has a function called getRaster(), this function returns a Raster object. On that use getDataBuffer(). That's the hardcore representation :) of your image - a single array. You can read and write there (to modify the image), and it's the fastest possible way to access this image's data. It once improved application speed in one of my programs by a factor of about 100 (no kidding). The elements are arranged as follows:

index = width * y + x

There you can read the integer HEX value (as in your browser, 0xFFFFFF being white) that identifies your color. Use binary and's and or's to get the RGB value out of that - or you can create a new Color with the value (as a constructor value) and then get the RGB values out of there.

Code for obtaining the pixel's color (theoretically, de facto I have never done this):

Code:
int value = getValue(x, y);
int redMask = 0xff0000;
int redDivider = 0x100000;
int greenMask = 0x00ff00;
int redDivider = 0x001000;
int blueMask = 0x0000ff;
int blueDivider = 0x000010;
int redValue = value & redMask / redDivider;
int greenValue = value & greenMask / greenDivider;
int blueValue = value & blueMask / blueDivider;

Alternatively use a PixelGrabber - search the web for a tutorial on that (I once found one, there really are some :)), it will probably be easier (yet slower) than the hardcore approach...
allow thyself to be the spark that lights the fire
haslo@haslo.ch - www.haslo.ch​
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top