2012-02-05 120 views
1

我正在开发一个项目并安静地使用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(); 
     } 
    } 
} 
+0

您确定图片有青色像素吗?顺便说一句,如果你打算在找到第一个像素后关闭文件,那么你应该停止循环。如果发现第二个像素,则会生成IOException,因为当您尝试写入时,out将已经关闭。) – 2012-02-05 07:26:55

+0

您可以使用['Zoom'](http://stackoverflow.com/a/3742841/230513 )查看桌面上任何像素的RGB分量。 – trashgod 2012-02-05 08:57:16

+0

你应该寻找颜色__如青色,而不是_cyan_ – 2012-02-05 12:44:54

回答

3

这个问题可能是,你的birds.jpg图像不包含的像素,这正是R = 0,G = 255,B = 255(即青色)。即使您在Paint中打开图像并绘制蓝绿色像素,保存时也可能会稍微改变颜色,因为JPEG是有损格式。

你可以尝试测试是由与此更换你的if语句接近青色像素:

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

好吧,我得到这个工作,但不是> 255,因为颜色只有0-255。你能告诉我青色的范围..从哪里开始到255 ..? – 2012-02-06 06:21:58

+0

请注意我的答案是> 225,而不是> 255。我选择了30作为宽容(255-30 = 225),但宽容取决于你!青色没有官方范围。 – 2012-02-06 09:29:10

1

我觉得另一个问题是在你的if语句。你有图像寻找255以上的东西。但是,在java中,255是红色,蓝色或绿色的最大值。如果你正在寻找255,把它从color.getBlue() > 255 改为 color.getRed() == 255 希望这有助于!