如何在SQLite数据库上显示存储为BLOB的图像

时间:2017-03-26 23:47:06

标签: java android sqlite imageview blob

我是android studio的新手,我对此有困难。我在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);

在另一个课程中,我试图显示这个存储的图像,我遇到了很多麻烦。我之前从未遇到过BLOB。

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

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

当我尝试在此类中设置图像时,我收到一个错误,表明可以使用drawable。就像我说的那样,我对此非常陌生.`

1 个答案:

答案 0 :(得分:1)

  
    

cv5.put( “图片”, “club.png”); //这是一个错误的方式

  

您之前需要将图像转换为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);
相关问题