2012-02-08 55 views
2

我得到了一個小問題,我認爲,不難。但是不知何故,我想念「不可能很難」的一部分:)。如何使用顏色代碼聲明

我有一個代碼,讀取圖像的顏色:

bmp = BitmapFactory.decodeResource(getResources(), R.drawable.four_colors); 


    //define the array size 
    rgbValues = new int[bmp.getWidth()][bmp.getHeight()]; 

    //Print in LogCat's console each of one the RGB and alpha values from the 4 corners of the image 
    //Top Left 
    for (int j = 0; j < 1000; j++){ 
     for (int k = 0; k < 1000; k++){ 
    Log.i("Pixel Value", "pixel x="+j +k + Integer.toHexString(bmp.getPixel(j, k))); 
    test = Integer.toHexString(bmp.getPixel(j, k)); 


     } 
    } 

    //get the ARGB value from each pixel of the image and store it into the array 
    for(int i=0; i < bmp.getWidth(); i++) 
    { 
     for(int j=0; j < bmp.getHeight(); j++) 
     { 
      //This is a great opportunity to filter the ARGB values 
      rgbValues[i][j] = bmp.getPixel(i, j);    
     } 
    } 

    System.out.println(PixelNumber); 
    System.out.println(test); 
} 

此代碼的工作就像一個魅力。 但我試圖執行一個if語句,如:

if (color == black){ 
    number++; 
} 

所以每像素他看到是黑色的,他必須增加與1

幾乎嘗試了我能想出了做一個好一切的數量如果圍繞此代碼聲明,但似乎沒有任何工作。 那麼這個代碼中的正確位置和聲明是什麼?

也許如果你有更多的時間(不要放太多精力在這,如果你不想要的)是有可能只是代替1種顏色檢查色彩範圍,所以它選擇所有的綠色。 (與Photoshop中的顏色範圍相同)。

+1

從描述它無法理解你已經嘗試了if語句,不存在一提您的其他代碼中的任 – 2012-02-08 14:02:16

回答

1

getPixel返回一個整數ARGB的4字節。你應該做的是編寫你想要計算的顏色(argb方法Color將幫助你)並用getPixel(x, y)對此值進行測試。
爲黑色,這將是很容易:

if(Color.BLACK == bmp.getPixel(x, y)) 
    //doit 

對於範圍可以使用​​/red/blue方法,每個方法返回該組件的值。如果它不爲零,則該像素具有該組件的顏色。

+0

您將「int」與「Color」進行比較。這應該會導致編譯時錯誤。 – 2012-02-08 14:14:58

+0

Color.BLACK是一個int常數。看看文檔:http://developer.android.com/reference/android/graphics/Color.html#BLACK – zeller 2012-02-08 14:17:27

+0

@Andreas_D'顏色。BLACK'和'getPixel()'都是ints – DRiFTy 2012-02-08 14:17:33

0

你可以通過if(rgbValues [i] [j] == Color.BLACK)這樣的條件。

該代碼將如下所示。

//get the ARGB value from each pixel of the image and store it into the array 
    for(int i=0; i < bmp.getWidth(); i++) 
    { 
     for(int j=0; j < bmp.getHeight(); j++) 
     { 
      //This is a great opportunity to filter the ARGB values 

      rgbValues[i][j] = bmp.getPixel(i, j); 
      if(rgbValues[i][j] == Color.BLACK) { 

     } 
    } 
0

Bitmap#getPixel(int, int)返回代表給定像素的透明度(alpha)和顏色(rgb)的值int

黑色的RGB值爲(0x00, 0x00, 0x00)。所以,如果你想測試黑色忽略Alpha值,測試應該是這樣的:

if ((rgbValue[i][j] & 0x00ffffff) == 0) { 
    // this pixel is black 
    number++; 
} 

色彩範圍是非常困難的。首先,我們需要可計算的定義綠色(例如)。 綠色是非常主觀的。一旦你手頭上有一個算法,把它放在一個不同的方法,做這樣的呼籲:

if (isGreenish(rgbValue[i][j])) {  // magic method 
    // this pixel is some sort of green 
    number++; 
}