我正在编写一个程序,帮助我检查图像的任何像素中是否有特定的颜色。
这就是我目前所拥有的:
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();
}
}
我似乎无法让它运行,所以我很想得到一些关于如何以正确方式运行的提示。
我刚刚测试了您的代码。它确实有效。你只需要确保你使用的图像具有与你在代码中期望的相同的颜色强度。
例如,(看似)红色像素可能不一定是RGB (255, 0 , 0)
。图像格式也可能起到一定作用。
如果使用有损压缩图像格式(例如jpeg、png),则在保存过程中可能会更改颜色像素。
我在24位位图上测试了你的代码,它能够输出一些东西。你可以先在一些基本颜色上测试:
示例:
if(color.equals(Color.RED))
System.out.println("Red exist!");
也许它抛出iOException试试这个,为什么你会抛出一个你已经尝试捕获它的异常
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();
}
}
}
可以使用以下语法接收像素值:
Color c = new Color(image.getRGB(x, y));
然后,您可以在c.上调用getRed()/getGreen()/geblue()方法