我正在开发一个项目并安静地使用java。我想逐像素扫描一个特定的颜色,即青色,然后打印该像素颜色的坐标。该代码运行,创建一个输出文件,但不写任何东西。 有人可以帮助我找到错误。我也想知道如何在使用相同代码时阅读java中的.tiff
文件。在java中扫描某个特定像素颜色的图像
Java代码:
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();
}
}
}
您确定图片有青色像素吗?顺便说一句,如果你打算在找到第一个像素后关闭文件,那么你应该停止循环。如果发现第二个像素,则会生成IOException,因为当您尝试写入时,out将已经关闭。) – 2012-02-05 07:26:55
您可以使用['Zoom'](http://stackoverflow.com/a/3742841/230513 )查看桌面上任何像素的RGB分量。 – trashgod 2012-02-05 08:57:16
你应该寻找颜色__如青色,而不是_cyan_ – 2012-02-05 12:44:54