2010-11-30 102 views
1

在我的項目中,我有一個位圖圖像。我需要將此圖片轉換爲byteArray以便處理一些字節,然後將其保存爲圖像。Android:將圖像轉換爲字節Arrayrayray

使用此代碼image = BitmapFactory.decodeResource(context.getResources(), R.drawable.tasnim);我有訪問寬度和高度,但我怎麼可以訪問此圖像的字節?

感謝

回答

2

我假設OP想要操縱像素,而不是圖像的頭部信息...

假設你imageBitmap

int w = image.getWidth(), h = image.getHeight(); 
int[] rgbStream = new int[w * h]; 
image.getPixels(rgbStream, 0, w, 0, 0, w, h); 

當然,這會讓你的像素值爲整數...但是你總是可以再次轉換它們。

int t = w * h; 

    for (int i = 0; i < t; i++) { 
     pixel = rgbStream[i]; //get pixel value (ARGB) 
     int A = (pixel >> 24) & 0xFF; //Isolate Alpha value... 
     int R = (pixel >> 16) & 0xFF; //Isolate Red Channel value... 
     int G = (pixel >> 8) & 0xFF; //Isolate Green Channel value... 
     int B = pixel & 0xFF; //Isolate Blue Channel value... 
         //NOTE, A,R,G,B can be cast as bytes... 


    } 
+0

感謝酷st0le,但我有一個問題。我認爲在位圖圖像中,每個像素包含3個字節的R,G和B.因此,我應該在第二行寫入int [w * h * 3]而不是int [w * h]嗎? – Hesam 2010-11-30 14:32:23

+0

哦,我認爲每個整數包含4個字節,所以不需要* 3.正確? – Hesam 2010-11-30 14:52:00

3

據我所知最正確的方法是:

ByteBuffer copyToBuffer(Bitmap bitmap){ 
    int size = bitmap.getHeight() * bitmap.getRowBytes(); 
    ByteBuffer buffer = ByteBuffer.allocateDirect(size); 
    bitmap.copyPixelsToBuffer(buffer); 
    return buffer; 
}