2014-03-03 106 views
0

我正在使用android項目,在我的項目中,我想將圖像的像素值存儲到數組中,我使用getPixels()函數並將其存儲在數組中命名爲像素,但是當我試圖在TextView中打印它時,我得到了一些像-1623534等這樣的antinh值。爲什麼它是這樣的。 ?從圖像獲取像素值時出現錯誤

這裏是我的代碼: -

Bitmap result = BitmapFactory.decodeFile(filePath); 
     TextView resultText=(TextView)findViewById(R.id.txtResult); 
     try 
     { 
      int pich=(int)result.getHeight(); 
      int picw=(int)result.getWidth(); 

      int[] pixels = new int[pich*picw]; 
      result.getPixels(pixels, 0, picw, 0, 0, picw, pich); 


      //To convert into String 

      StringBuffer buff = new StringBuffer(); 
      for (int i = 0; i <100; i++) 
       { 
        // getting values from array 
       buff.append(pixels[i]).append(" "); 
       } 


      //To save the binary in newString 

      String newString=new String(buff.toString()); 

      resultText.setText(newString); 

而且我在其他一些後發現,像

  int R, G, B; 

      for (int y = 0; y < pich; y++) 
      { 
       for (int x = 0; x < picw; x++) 
       { 
        int index = y * picw + x; 
        R = (pixels[index] >> 16) & 0xff;  //bitwise shifting 
        G = (pixels[index] >> 8) & 0xff; 
        B = pixels[index] & 0xff; 

        //R,G.B - Red, Green, Blue 
        //to restore the values after RGB modification, use 
        //next statement 
        pixels[index] = 0xff000000 | (R << 16) | (G << 8) | B; 
       } 
      } 

所以我修改了代碼: -

Bitmap result = BitmapFactory.decodeFile(filePath); 
     TextView resultText=(TextView)findViewById(R.id.txtResult); 
     try 
     { 
      int pich=(int)result.getHeight(); 
      int picw=(int)result.getWidth(); 

      int[] pixels = new int[pich*picw]; 
      result.getPixels(pixels, 0, picw, 0, 0, picw, pich); 

      int R, G, B; 

      for (int y = 0; y < pich; y++) 
      { 
       for (int x = 0; x < picw; x++) 
       { 
        int index = y * picw + x; 
        R = (pixels[index] >> 16) & 0xff;  //bitwise shifting 
        G = (pixels[index] >> 8) & 0xff; 
        B = pixels[index] & 0xff; 

        //R,G.B - Red, Green, Blue 
        //to restore the values after RGB modification, use 
        //next statement 
        pixels[index] = 0xff000000 | (R << 16) | (G << 8) | B; 
       } 
      } 

      //To convert into String 

      StringBuffer buff = new StringBuffer(); 
      for (int i = 0; i <100; i++) 
      { 
        // getting values from array 
       buff.append(pixels[i]).append(" "); 
      } 


      //To save the binary in newString 

      String newString=new String(buff.toString()); 

      resultText.setText(newString); 

是否正確?即使在修改之後,我也會得到一些值得信賴的值,請幫助我,請提前致謝

回答

1

獲取負值的原因如下: 圖像的每個像素包含4個值(紅色,綠色,藍色,alpha )。每個值都有8位(一個字節)。所有4個一起都有32位,這是一個整數值的大小。但是當你打印一個(帶符號的)整數時,第一位被解釋爲符號標誌,所以如果這個位被設置爲1(當第一個通道> = 128時發生),你可以得到負值。

要想從像素RGB值我通常使用這樣的:

int pixel = bmp.getPixel(x, y); 
int red = Color.red(pixel); 
int green = Color.green(pixel); 
int blue = Color.blue(pixel); 
+0

我不想有RGB值可言,我只需要在我的項目的像素值 – Abinthaha

相關問題