Hesam
Hesam

Reputation: 53600

Android: conerting Image into byteArray

In my project I have an bitmap image. I need to convert this picture to byteArray in order to manipulate some bytes and after that save it as image.

with this code image = BitmapFactory.decodeResource(context.getResources(), R.drawable.tasnim); I have acces to width and height but how can I have access to bytes of this image?

Thanks

Upvotes: 1

Views: 5353

Answers (2)

st0le
st0le

Reputation: 33545

I'm assuming the OP wants to manipulate the pixels, not the header information of the Image...

Assuming your image is a Bitmap

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

Of course, this gets you Pixel values as Integers...But you can always convert them again.

    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...


    }

Upvotes: 2

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

AFAIK Most correct way is:

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

Upvotes: 3

Related Questions