2015-12-17 77 views
0

我想编写一个程序,帮助我检查图像的任何像素是否存在某种颜色。扫描一个图像的某种颜色存在

这是我到目前为止有:

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(); 
    } 
} 

我似乎无法得到它的运行,所以我很想得到关于如何做到这一点的正确方法的提示。

+0

具体是什么,你的“我不能让它跑”呢?它是否构建?如果它构建,它会做什么? – nicomp

+0

你得到的错误 –

+0

“BufferedImage类型中的方法getRGB(int,int)不适用于参数()” – marcelxvi

回答

0

也许它抛出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(); 
    } 
} 
} 
+0

刚刚尝试过,没有解决我的问题 – marcelxvi

0

可以使用下面的语法接收像素值:

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

然后,您可以在c上调用您的getRed()/ getGreen()/ getBlue()方法。

+0

只是把它改为从c传出。它没有解决我的问题tho,仍然没有输出 – marcelxvi

+0

如果没有找到匹配的像素,请在if函数中添加else语句来打印某些内容。您正在扫描的图像可能没有与您正在查看的图像相匹配的像素。 – Joopkins

1

我刚刚测试了你的代码。它实际上工作。您只需确保您使用的图像具有与您在代码中所期待的相同的颜色强度。

例如,(看似)红色像素可能不需要为RGB (255, 0 , 0)。图像格式也可能起作用。

如果使用有损压缩图像格式(例如jpeg,png),则在保存过程中可能会更改彩色像素。

我在24位位图上测试了你的代码,它能够输出一些东西。您可以在一些基本的颜色首先测试它:

例子:

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

**备注:**我刚做了另一项测试,它也适用于有损图像格式。然后,我现在更确定您用于测试的图像可能不包含与您的条件中指定颜色强度相匹配的彩色像素。 – user3437460

+0

@marcelxvi检查你的图像,让我知道它是否工作。 – user3437460

相关问题