1

I have ImageButton when click on it gallery will appear for pick an image and send bitmap back to show on this ImageButton. But I have to get bitmap that has been shown on this ImageButton and then save it into database as byte[]

Basil jose
  • 718
  • 3
  • 10
freeman
  • 82
  • 10

4 Answers4

2

first get the bitmap from the ImgaeButton

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();

then convert this bitmap to byteArray

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
Sachin
  • 4,110
  • 2
  • 16
  • 27
1

When you load image from gallery, you already have the URI reference to it, or you have the bitmap. Hope the following helps

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

Now, if you want to get bitmap from imageButton, you can use

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();

Refer How to get Bitmap from an Uri? as well, to know more

Maria
  • 194
  • 1
  • 5
0

Try

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();
Liar
  • 1,175
  • 1
  • 8
  • 19
0

You can use a blob to store an image in sqlite android internal db.

*** below answer is completely copied from How to store image in SQLite database - credit goes to answer provider

public void insertImg(int id , Bitmap img ) {

    byte[] data = getBitmapAsByteArray(img); // this is a function

    insertStatement_logo.bindLong(1, id);       
    insertStatement_logo.bindBlob(2, data);

    insertStatement_logo.executeInsert();
    insertStatement_logo.clearBindings() ;

}

 public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, outputStream);       
    return outputStream.toByteArray();
}

to retrieve a image from db

public Bitmap getImage(int i){

String qu = "select img  from table where feedid=" + i ;
Cursor cur = db.rawQuery(qu, null);

if (cur.moveToFirst()){
    byte[] imgByte = cur.getBlob(0);
    cur.close();
    return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
if (cur != null && !cur.isClosed()) {
    cur.close();
}       

return null ;
} 
PushpikaWan
  • 2,284
  • 2
  • 12
  • 22