android - converting Java bitmap to byte array

ID : 9834

viewed : 216

Tags : javaandroidserializationbitmapbytebufferjava





Top 5 Answer for android - converting Java bitmap to byte array

vote vote

98

Try something like this:

Bitmap bmp = intent.getExtras().get("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); bmp.recycle(); 
vote vote

80

CompressFormat is too slow...

Try ByteBuffer.

※※※Bitmap to byte※※※

width = bitmap.getWidth(); height = bitmap.getHeight();  int size = bitmap.getRowBytes() * bitmap.getHeight(); ByteBuffer byteBuffer = ByteBuffer.allocate(size); bitmap.copyPixelsToBuffer(byteBuffer); byteArray = byteBuffer.array(); 

※※※byte to bitmap※※※

Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name()); Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp); ByteBuffer buffer = ByteBuffer.wrap(byteArray); bitmap_tmp.copyPixelsFromBuffer(buffer); 
vote vote

80

Here is bitmap extension .convertToByteArray wrote in Kotlin.

/**  * Convert bitmap to byte array using ByteBuffer.  */ fun Bitmap.convertToByteArray(): ByteArray {     //minimum number of bytes that can be used to store this bitmap's pixels     val size = this.byteCount      //allocate new instances which will hold bitmap     val buffer = ByteBuffer.allocate(size)     val bytes = ByteArray(size)      //copy the bitmap's pixels into the specified buffer     this.copyPixelsToBuffer(buffer)      //rewinds buffer (buffer position is set to zero and the mark is discarded)     buffer.rewind()      //transfer bytes from buffer into the given destination array     buffer.get(bytes)      //return bitmap's pixels     return bytes } 
vote vote

67

Do you need to rewind the buffer, perhaps?

Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.

vote vote

51

Use below functions to encode bitmap into byte[] and vice versa

public static String encodeTobase64(Bitmap image) {     Bitmap immagex = image;     ByteArrayOutputStream baos = new ByteArrayOutputStream();     immagex.compress(Bitmap.CompressFormat.PNG, 90, baos);     byte[] b = baos.toByteArray();     String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);     return imageEncoded; }  public static Bitmap decodeBase64(String input) {     byte[] decodedByte = Base64.decode(input, 0);     return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); } 

Top 3 video Explaining android - converting Java bitmap to byte array







Related QUESTION?