marcelxvi
marcelxvi

Reputation: 21

Scanning an image for a certain color to exist

I'm trying to code a program that helps me checking if there's a certain color in any pixel of an image.

This is what I have so far:

public static void main(String args[]) throws IOException {
    try {
        //read image file
        File file1 = new File("./Scan.png");
        BufferedImage image1 = ImageIO.read(file1);

        //write file
        FileWriter fstream = new FileWriter("log1.txt");
        BufferedWriter out = new BufferedWriter(fstream);

        for (int y = 0; y < image1.getHeight(); y++) {
            for (int x = 0; x < image1.getWidth(); x++) {

                int c = image1.getRGB(x,y);
                Color color = new Color(c);

                if (color.getRed() < 50 && color.getGreen() > 225 && color.getBlue() > 43) {
                    out.write("Specified Pixel found at=" + x + "," + y);
                    out.newLine();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I can't seem to get it to run, so I'd love to get some hints on how to do this the right way.

Upvotes: 0

Views: 636

Answers (3)

user3437460
user3437460

Reputation: 17454

I just tested your code. It actually works. You just have to ensure the image you are using is having the same color intensity as you are expecting in your codes.

For example, a (seemingly) red pixel may not necessary be RGB (255, 0 , 0). The image format may plays a part too.

If you use lossy compression image formats (e.g. jpeg, png), the color pixels might be altered during the saving process.

I tested your codes on 24bit-bitmap, it is able to output something. You can test it on some basic color first:

Example:

if(color.equals(Color.RED))
    System.out.println("Red exist!");

Upvotes: 1

Joopkins
Joopkins

Reputation: 1644

The pixel value can be received using the following syntax:

Color c = new Color(image.getRGB(x, y));

You can then call your getRed()/getGreen()/getBlue() methods on c.

Upvotes: 0

Mohammad Al Baghdadi
Mohammad Al Baghdadi

Reputation: 377


Maybe it throws iOException try this one why would you throw an exception that you already try catch it

public static void main(String args[]){
    try {
        //read image file
        File file1 = new File("./Scan.png");
        BufferedImage image1 = ImageIO.read(file1);

        //write file



        for (int y = 0; y < image1.getHeight(); y++) {
            for (int x = 0; x < image1.getWidth(); x++) {

              int c = image1.getRGB(x,y);
              Color color = new Color(c);

               if (color.getRed() < 50 && color.getGreen() > 225 && color.getBlue() > 43) {
                    System.out.println(x + "," + y);


                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Upvotes: 0

Related Questions