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

标签 java android sqlite imageview blob

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

我收到一个错误,提示需要一个可绘制对象。

最佳答案

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/

相关文章:

ios - 是否可以使用 sqlcipher 在 iOS 上使用全文搜索?

python - 为什么在我的 python sqlite SELECT 结果中得到额外的逗号?

python - 无论我尝试多少种不同的类型,插入语句永远不会起作用。 SQLite3 pyscripter

java - 使用 Mina 模拟 XMPP 服务器仅在部分时间有效

java - 在 Java Servlet 中限制 HTTP 请求

java - RestTemplate.exchange 创建实例,即使变量注释为 @NotNull

Android - 连接测试结果目录

android - 如何从 servlet 响应到客户端?

java - 在终端中运行 sbt 时卡在 "Getting org.scala-sbt sbt 0.13.6 ..."

android - RecyclerView 更改数据集