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
  • 774
  • 3
  • 11
freeman
  • 92
  • 11

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 Rajput
  • 4,326
  • 2
  • 18
  • 29
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
  • 369
  • 2
  • 7
0

Try

Bitmap bitmap = ((BitmapDrawable)imageButton.getDrawable()).getBitmap();
Liar
  • 1,235
  • 1
  • 9
  • 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,437
  • 3
  • 14
  • 23