android 如何显示存储为BLOB的图像?

oxcyiej7  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(245)

我使用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);
}

我收到一个错误,指出应该是drawable。

erhoui1w

erhoui1w1#

(“图片”,“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);

相关问题