Reputation: 33
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 .tiff
file in java while using the same code.
Java Code:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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 = ImageIO.read(file1);
//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);
out.newLine();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Views: 12876
Reputation: 345
I think another problem is in your if statement. You have the image looking for something GREATER than 255. However, in java, 255 is the max value you can have for red, blue, or green. If you are looking for exactly 255, change it from color.getBlue() > 255
to
color.getRed() == 255
Hope this helps!
Upvotes: 1
Reputation: 46456
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) {
Upvotes: 3