Sign in to follow this  

[java] BufferedImage

This topic is 4270 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can anyone help me out with understanding the buffered image class. I can use it to draw and load images but i need somehow to extract the array of pixels from inside of it. I need to do tests based on color of the pixels but it seems that the color is stored in an int variable. I understand that to make this variable for the pixel your pr together color arguments, but how do i find out the color of the pixel and use it to make a Color object? Ive serached on google and looked in a few books but found mostly info on creating Buffered Images. Thanks guys :-)

Share this post


Link to post
Share on other sites
I took the following code from this tutorial.


int bytesPerPixel = -1, pix;

// 3 or 4 bytes per pixel?
if( img.getColorModel().hasAlpha() )
bytesPerPixel = 4;
else
bytesPerPixel = 3;

// Allocate a ByteBuffer
ByteBuffer unpackedPixels =
ByteBuffer.allocateDirect(img.getWidth() * img.getHeight() * bytesPerPixel);

// Pack the pixels into the ByteBuffer in RGBA, 4 byte format.
for(int row = img.getHeight() - 1; row >= 0; row--) {
for (int col = 0; col < img.getWidth(); col++) {
pix = img.getRGB(col,row); // Should return the pixel in format TYPE_INT_ARGB
unpackedPixels.put((byte) ((pix >> 16) & 0xFF)); // red
unpackedPixels.put((byte) ((pix >> 8 ) & 0xFF)); // green
unpackedPixels.put((byte) ((pix ) & 0xFF)); // blue
if (bytesPerPixel == 4) {
unpackedPixels.put((byte) ((pix >> 24) & 0xFF)); // alpha
}
}
}


The page's link.

Son Of Cain

Share this post


Link to post
Share on other sites
im not so good with bytes, is there some way to use this data to make Color objects? It was helpfull though. Ty

Hey cant you just pass the int you get from the buffered image right to a color object? ill try that.

Share this post


Link to post
Share on other sites
Bytes are nothing to worry about, just think of them as a very small int. And yes, just passing the int should work, although if you're creating a Color object for each pixel its likely to take up a fair bit of memory if you have large images

Share this post


Link to post
Share on other sites

This topic is 4270 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this