从数据库显示图像(位图错误)

时间:2018-01-06 16:07:42

标签: android database sqlite bitmap android-bitmap

我必须按钮:第一个按钮用于将图像从图库保存到数据库,第二个按钮用于在imageView中显示来自数据库的图像,但我的第二个按钮的问题是此行的错误: " Bitmap bitmapImage = BitmapFactory.decodeFile(imageFile.toString());"

logcat错误中的

" E / BitmapFactory:无法解码流:java.io.FileNotFoundException:[B @ c97f202:open failed:ENOENT(没有这样的文件或目录)"

数据库代码:

private static String dbNAME = "myDB.db";
    private static String tableName = "imageColumns";
    private static String imageColumnName = "image";
    private Bitmap bitmap;
    private int i = 1;

    db = this.openOrCreateDatabase(dbNAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
    db.setVersion(1);
    db.setLocale(Locale.getDefault());

    String createTable = "create table if not exists imageColumns(id INTEGER PRIMARY KEY AUTOINCREMENT , image TEXT)";
    db.execSQL(createTable);

第一个按钮(保存图像)代码:

    public void save(View view) {
    if (bitmap != null) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        byte[] byteImage = stream.toByteArray();

        ContentValues values = new ContentValues();
        values.put(imageColumnName, String.valueOf(byteImage));

        db.insert(tableName, null, values);

        Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Save Image First!", Toast.LENGTH_SHORT).show();
    }


}

第二个按钮(显示图像)代码:

public void showImage(View view) {

    Cursor cursor2 = db.rawQuery("select * from imageColumns where id = " + i, null);
    if (cursor2.getCount() != 0) {
        while (cursor2.moveToNext()) {
            Toast.makeText(this, "number of images" + i, Toast.LENGTH_SHORT).show();
            String path = cursor2.getString(cursor2.getColumnIndex(imageColumnName));
            File imageFile = new File(path);
            Bitmap bitmapImage = BitmapFactory.decodeFile(imageFile.toString());
                 imageView.setImageBitmap(bitmapImage); //this line is problem
       }
        i++;
    }

}

1 个答案:

答案 0 :(得分:1)

public byte[] convetBitmapToByteArray(Bitmap bm)
{
    int size = bm.getRowBytes() * bm.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    bm.copyPixelsToBuffer(byteBuffer);
   return byteBuffer.array();
}
public Bitmap convertByteToBitmap(byte[] evidence)
{
    Bitmap bmp= BitmapFactory.decodeByteArray(evidence, 0, evidence.length);
    return bmp;
}

使用以上两种方法来存储和检索图像到表。 您应该在表中创建一个BLOB类型的列,它可以存储字节数组,所以首先必须将位图转换为字节数组,然后将其插入表中,当您检索记录时,您将获得该字节数组,因此将其转换返回位图将其设置为imageView。