2013-04-22 45 views
1

你好我想創造一個PROGRAMM讀取的圖像中的RGB值和後輸出的Excel,像這樣---圖像>http://www.boydevlin.co.uk/images/screenshots/eascreen04.png填充一個ArrayList與圖像的每個像素

爲了實現這一我想我已經從圖像中每個像素的RGB值讀取到一個ArrayList 我想將它保存在以下順序

例5x5px圖片

01,02,03,04,05 
06,07,08,09,10 
11,12,13,14,15 
....... 

我媒體鏈接有這一點,但它不工作出正確可能有人helpe我與algorrithm

public class Engine { 

    private int x = 0; 
    private int y = 0; 
    private int count = 50; 
    private boolean isFinished = false; 
    ArrayList<Color> arr = new ArrayList<Color>(); 

    public void process(){ 
     BufferedImage img = null; 
     try { 
      img = ImageIO.read(new File("res/images.jpg")); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.out.println("img file not found"); 
     } 

     while(isFinished = false){ 
     int rgb = img.getRGB(x, y); 
     Color c = new Color(rgb); 
     arr.add(c); 
     System.out.println("y:"+ y); 
     x++;} 
     if(x == 49){ 
      y++; 
      x = 0; 
      }else if(x == 49 && y == 49){ 
       isFinished = true; 
      } 
     } 

}; 
+0

你得到什麼錯誤? – jmrodrigg 2013-04-22 09:53:01

回答

1

你需要知道,如果圖像將成爲大,ArrayList會非常大,更好地使用普通數組(你知道.. []),並使其成爲兩個微觀的。 更好的是,如果您可以在適當的位置創建excel並且不將所有數據保存在數組中,只需在將數據寫入控制檯的地方設置適當的值即可。 我沒有測試過代碼,但應該沒問題。 如果您收到任何異常內容,以便我們提供幫助。

嘗試類似的東西:

public class Engine { 

    private int x = 0; 
    private int y = 0; 
    ArrayList<Color> arr = new ArrayList<Color>(); 

    public void process() { 
     BufferedImage img = null; 
     try { 
      img = ImageIO.read(new File("res/images.jpg")); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      System.out.println("img file not found"); 
     } 

     for(int x=0;x<img.getWidth();x++){ 
      for(int y=0;y<img.getHeight();y++){ 
       int rgb = img.getRGB(x, y); 
       Color c = new Color(rgb); 
       arr.add(c); 
       System.out.println("x: "+ x + " y:" + y +" color: " + c); 
      } 
     } 
    } 
}; 
2

首先:你有一個錯誤在while

從它轉換:

while (isFinished=false)

while (isFinished==false) 

第二:使用for循環,而不是while

for (int x = 0; x < img.getWidth(); x++) { 
      for (int y = 0; y < img.getHeight(); y++) { 
       int rgb = img.getRGB(x, y); 
       Color c = new Color(rgb); 
       arr.add(c); 
      } 

     } 

,如果你使用while循環想要的話,試試這個:

while (isFinished == false) { 
      int rgb = img.getRGB(x, y); 
      Color c = new Color(rgb); 
      arr.add(c); 
      x++; 
      if (x == img.getWidth()) { 
       y++; 
       x = 0; 
      } else if (x == img.getWidth() - 1 && y == img.getHeight() - 1) { 
       isFinished = true; 
      } 
     } 
+1

+1 for for循環。 – jmrodrigg 2013-04-22 10:02:21