What is the fastest way to get the RGB value of each pixel of a BufferedImage
?
Right now I am getting the RGB values using two for
loops as shown in the code below, but it took too long to get those values as the nested loop runs a total of 479999 times for my image. If I use a 16-bit image this number would be even higher!
I need a faster way to get the pixel values.
Here is the code I am currently trying to work with:
BufferedImage bi=ImageIO.read(new File("C:\\images\\Sunset.jpg"));
int countloop=0;
for (int x = 0; x <bi.getWidth(); x++) {
for (int y = 0; y < bi.getHeight(); y++) {
Color c = new Color(bi.getRGB(x, y));
System.out.println("red=="+c.getRed()+" green=="+c.getGreen()+" blue=="+c.getBlue()+" countloop="+countloop++);
}
}
I don't know if this might help and I haven't tested it yet but you can get the rgb values this way:
BufferedImage bi=ImageIO.read(new File("C:\\images\\Sunset.jpg"));
int[] pixel;
for (int y = 0; y < bi.getHeight(); y++) {
for (int x = 0; x < bi.getWidth(); x++) {
pixel = bi.getRaster().getPixel(x, y, new int[3]);
System.out.println(pixel[0] + " - " + pixel[1] + " - " + pixel[2] + " - " + (bi.getWidth() * y + x));
}
}
As you can see you don't have to initialize a new Color inside the loop. I also inverted the width/height loops as suggested by onemasse to retrieve the counter from data I already have.