我是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。就像我说的那样,我对此很陌生。''

最佳答案

cv5.put(“ Picture”,“ 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);

09-05 17:52
查看更多