According to Get color of each pixel of an image using BufferedImages, the following code needs for loops for its intended purpose to work.
public class GetPixelColor
{
public static void main(String args[]) throws IOException{
File file= new File("your_file.jpg");
BufferedImage image = ImageIO.read(file);
// Getting pixel color by position x and y
int clr= image.getRGB(x,y);
int red = (clr & 0x00ff0000) >> 16;
int green = (clr & 0x0000ff00) >> 8;
int blue = clr & 0x000000ff;
System.out.println("Red Color value = "+ red);
System.out.println("Green Color value = "+ green);
System.out.println("Blue Color value = "+ blue);
}
}
How do I define the region of the image I would like to check for its color with for loops?
the region you want to read it's color is a rectangle between two points p1(x1,y1), p2(x2,y2) and you scan that rectangle by two nested for loops like this
for(int x=x1; x<=x2; x++)
for(int y=y1; y<=y2; y++){
// Getting pixel color by position x and y
int clr= image.getRGB(x,y);
int red = (clr & 0x00ff0000) >> 16;
int green = (clr & 0x0000ff00) >> 8;
int blue = clr & 0x000000ff;
System.out.println("Red Color value = "+ red);
System.out.println("Green Color value = "+ green);
System.out.println("Blue Color value = "+ blue);
}
You can simply use two nested for loops to loop through the image, something like this:
public static void printPixelColors(BufferedImage img) {
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
for (int y = 0; y < imageHeight; y++) {
for (int x = 0; x < imageWidth; x++) {
// Getting pixel color by position x and y
int clr = img.getRGB(x, y);
int red = (clr & 0x00ff0000) >> 16;
int green = (clr & 0x0000ff00) >> 8;
int blue = clr & 0x000000ff;
System.out.println("Red Color value = " + red);
System.out.println("Green Color value = " + green);
System.out.println("Blue Color value = " + blue);
}
}
}
User contributions licensed under CC BY-SA 3.0