Sandra123
Sandra123

Reputation: 39

How to display an image stored as a BLOB?

I stored an image in an SQLite database using Android Studio:

public void onCreate(SQLiteDatabase db){
        db.execSQL(create_table);
    }

private static final String create_table = "create table if not exists Test ("+
            "EntryID integer primary key autoincrement, "+
            "Description string,"+
            "Picture blob"+
            ")";

Insert into database :

ContentValues cv5 = new ContentValues();
    cv5.put("EntryID",1);
    cv5.put("Description","The club was founded in 1885";
    cv5.put("Picture","club.png");
    sdb.insert("Test",null,cv5);

Attempting to display stored image:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Drawable myDrawable = getResources().getDrawable(R.drawable.club);
    image.setImageDrawable(myDrawable);
}

I get an error that a drawable is expected.

Upvotes: 0

Views: 3502

Answers (1)

Radmir Tsyhulskyi
Radmir Tsyhulskyi

Reputation: 109

cv5.put("Picture","club.png"); // it's a WRONG way

You need previously convert image to BLOB, something like that

ByteArrayOutputStream outStreamArray = new ByteArrayOutputStream();  
    Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStrea);   
    byte[] photo = outStreamArray.toByteArray();cv5.put("Picture", photo)

After that you need decode BLOB to image

  byte[] photo=cursor.getBlob(index of blob cloumn);
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap bitmap= BitmapFactory.decodeStream(imageStream);
image.setImageBitmap(bitmap);

Upvotes: 1

Related Questions