[JAVA] Mutual conversion of Bitmap / JPEG / byte array on Android

Handling of image data

When I was creating an application that reads an image file and processes it, I sometimes wanted to convert various image formats (jpeg, png, bmp, etc.) to Bitmap class and handle it. On the contrary, there were also cases where I wanted to compress jpeg / png from Bitmap or convert it to a byte array. In this article, I will make a note of their mutual conversion.

How to convert formats

In this article, in order to distinguish between "** Bitmap class " and " image format bitmap " of Android SDK, the former is " Bitmap " and the latter is " bmp **". It is written as ".

byte array (bmp) → Bitmap

Bitmap.create Bitmap is created by specifying the vertical and horizontal size of the image and the bmp format in Bitmap (). Copy the byte array to the contents of the generated Bitmap via ByteBuffer.

bmparr2bitmap.java


// bmparr(byte[])Assuming that the image data is in bmp format
// width, height:Image data size
Bitmap bitmap = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(bmparr));

byte array (jpeg, png, etc.) → Bitmap

Use BitmapFactory.decodeByteArray (). This method decodes the data compressed by jpeg or png to Bitmap. It seems that the bmp format cannot be decoded here.

jpegarr2bitmap.java


// jpgarr(byte[])Assuming that the image data is in a compressed format such as jpeg or png
Bitmap bitmap = BitmapFactory.decodeByteArray(jpgarr, 0, jpgarr.length);

Bitmap → byte array (bmp format)

Copy the value to ByteBuffer with Bitmap.copyPixelsToBuffer () and extract the byte array from ByteBuffer.

bitmap2bmparr.java


// bitmap(Bitmap)Premise that image data is included in
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(byteBuffer);
byte[] bmparr = byteBuffer.array();

Bitmap → byte array (jpeg, png, etc.)

Compress from Bitmap to format such as jpeg / png with Bitmap.compress () and pass it to ByteArrayOutputStream. Extract a byte array from a ByteArrayOutputStream.

bitmap2jpgarr.java


// bitmap(Bitmap)Premise that image data is included in
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] jpgarr = baos.toByteArray();

Recommended Posts

Mutual conversion of Bitmap / JPEG / byte array on Android
Java array / list / stream mutual conversion list
12 of Array
Browse an instance of Tab's View on Android