我使用 Android Studio 将图像存储在 SQLite 数据库中:
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"+
")";
插入数据库:
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);
尝试显示存储的图像:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawable myDrawable = getResources().getDrawable(R.drawable.club);
image.setImageDrawable(myDrawable);
}
我收到一个错误,提示需要一个可绘制对象。
最佳答案
block 引用>cv5.put("Picture","club.png"); // it's a WRONG way
您需要事先将图像转换为 BLOB,类似的东西
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)
之后您需要将 BLOB 解码为图像
byte[] photo=cursor.getBlob(index of blob cloumn); ByteArrayInputStream imageStream = new ByteArrayInputStream(photo); Bitmap bitmap= BitmapFactory.decodeStream(imageStream); image.setImageBitmap(bitmap);
关于java - 如何显示存储为 BLOB 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43035939/