JJJollyjim
JJJollyjim

Reputation: 6207

Finding the color at coordinates in a PNG image in Java

With a URL of a PNG image (or the data at that url, in String form), how could one use Java to find the RGB (or similar) value at a set of coordinates?

Thanks in advance!

Upvotes: 0

Views: 2137

Answers (1)

icyrock.com
icyrock.com

Reputation: 28588

This example should have all you need:

To cite the relevant part of the thread:

File inputFile = new File("image.png");
BufferedImage bufferedImage = ImageIO.read(inputFile);
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight(null);

//Get Pixels
int [] rgbs = new int[w*h];
bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w); //Get all pixels

and then to get a particular pixel, see the docs:

i.e.:

int pixel = rgbs[offset + (y-startY)*scansize + (x-startX)];

If you just want one pixel, you can use getRGB(x, y):

i.e.:

int pixel = bufferedImage.getRGB(x, y);

Upvotes: 1

Related Questions