Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

object - Android: problem retrieving bitmap from database

When I'm retrieving image from the sqlite database my Bitmap object bm return null value can any one help me..?

I found problem in my database..

When I store the byte array in blob data type in database table that time the size of the byte array was 2280..

But when i retrieved that blob data type using select query I get the byte array within size 12.

My code is:

// Inserting data in database
byte[] b;  
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.icon);  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object  
b = baos.toByteArray();  
//here b size is 2280  
baos.close();  
try  
{  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");    
mDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+ " (PICTURE)"
+ " VALUES ('"+b+"');");  

}  
catch(Exception e)  
{  
Log.e("Error", "Error", e);  
}  

finally  
{  
if(mDB != null)  
mDB.close();  
}  


// Retriving data from database  
byte[] b1;  
Bitmap bm;  
mDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);  
try {  
mDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+ " (PICTURE BLOB);");  

Cursor c = mDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + ";", null);  
c.moveToFirst();  
if (c != null) {  
do {  
b1=c.getBlob(0)); //here b1 size is 12   
bm=BitmapFactory.decodeByteArray(b1, 0, b1.length);   
}while(c.moveToNext());  
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's how I encode the image before writing to the database:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray();  // write this to database as blob

And then decode it like the from Cursor:

ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...