me erum me erum - 11 months ago 77
Java Question

scanning an image for a certain pixel color in java

I'm working on a project and quiet new to java. I want to scan an image pixel by pixel for a certain color, i.e. cyan and then print the coordinates of that pixel color. The code runs, creates an output file but doesn't write anything to it.
Can somebody please help me with it to find the errors. I also want to know how to read a

file in java while using the same code.

Java Code:

import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class GetPixelColor {

//int y, x, tofind, col;
* @param args the command line arguments
* @throws IOException
public static void main(String args[]) throws IOException {
try {
//read image file
File file1 = new File("E:\\birds.jpg");
BufferedImage image1 =;

//write file
FileWriter fstream = new FileWriter("E:\\pixellog1.txt");
BufferedWriter out = new BufferedWriter(fstream);

//color object
//Color cyan = new Color(0, 255, 255);

//find cyan pixels
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);

//int red = (c & 0x0000FFFF) >> 16;
//int green = (c & 0x0000FFFF) >> 8;
//int blue = c & 0x0000FFFF;

//if (cyan.equals(image1.getRGB(x, y)){

if (color.getRed() < 30 && color.getGreen() > 255 && color.getBlue() > 255) {
out.write("CyanPixel found at=" + x + "," + y);

} catch (IOException e) {

Answer Source

The problem is probably that your birds.jpg image doesn't contain a pixel that is exactly r=0, g=255, b=255 (i.e. cyan). Even if you open the image in Paint and draw a cyan pixel, the color may get slightly altered when you save because JPEG is a lossy format.

You could try testing for pixels that are close to cyan by replacing your if statement with this:

Color c = new Color(image1.getRGB());
if (c.getRed() < 30 && c.getGreen() > 225 && c.getBlue() > 225) {