Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android- convert ARGB_8888 bitmap to 3BYTE_BGR

I get the pixel data of my ARGB_8888 bitmap by doing this:

public void getImagePixels(byte[] pixels, Bitmap image) {
    // calculate how many bytes our image consists of
    int bytes = image.getByteCount();

    ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
    image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer

    pixels = buffer.array(); // Get the underlying array containing the data.
}

But, I would like to convert this data, in which each pixel is stored on four bytes (ARGB), to where each pixel is stored on 3 bytes (BGR).
Any help is appreciated!

like image 236
Dylan Milligan Avatar asked Mar 23 '23 21:03

Dylan Milligan


1 Answers

Disclaimer: There could be better/easier/faster ways of doing this, using the Android Bitmap API, but I'm not familiar with it. If you want to go down the direction you started, here's your code modified to convert 4 byte ARGB to 3 byte BGR

public byte[] getImagePixels(Bitmap image) {
    // calculate how many bytes our image consists of
    int bytes = image.getByteCount();

    ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
    image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer

    byte[] temp = buffer.array(); // Get the underlying array containing the data.

    byte[] pixels = new byte[(temp.length / 4) * 3]; // Allocate for 3 byte BGR

    // Copy pixels into place
    for (int i = 0; i < (temp.length / 4); i++) {
       pixels[i * 3] = temp[i * 4 + 3];     // B
       pixels[i * 3 + 1] = temp[i * 4 + 2]; // G
       pixels[i * 3 + 2] = temp[i * 4 + 1]; // R

       // Alpha is discarded
    }

    return pixels;
}
like image 115
Harald K Avatar answered Mar 25 '23 11:03

Harald K