Convert bitmap to Byte array using ByteArrayOutputStream - Android android.graphics

Android examples for android.graphics:Bitmap Convert

Description

Convert bitmap to Byte array using ByteArrayOutputStream

Demo Code

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;

public class Main {

  public static byte[] bitmap2Bytes(Bitmap bitmap,
      Bitmap.CompressFormat mCompressFormat, final boolean needRecycle) {
    byte[] result = null;
    ByteArrayOutputStream output = null;
    try {/*  w  w  w .ja v  a  2s  .  c om*/
      output = new ByteArrayOutputStream();
      bitmap.compress(mCompressFormat, 100, output);
      result = output.toByteArray();
      if (needRecycle) {
        bitmap.recycle();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }

}

Related Tutorials