How to retrieve an image from a SQLite database?

*爱你&永不变心* 提交于 2019-12-13 08:15:40

问题


I am storing an image taken from camera into sqlite database can anybody help me to retrieve the same image and i want to show that image in a image view.

Here is my Database handler class method for saving the image

public long insert(Bitmap img ) {

        SQLiteDatabase base=this.getWritableDatabase();
        byte[] data = getBitmapAsByteArray(img); // this is a function
        ContentValues value=new ContentValues();
        value.put("image",data);

        long a= base.insert("Mypic", null, value); 
        System.out.println("check1" + a);

        return a; 
    }


    public static byte[] getBitmapAsByteArray(Bitmap bitmap) 
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 0, outputStream);
        return outputStream.toByteArray();
    } 

Please help me for writing the method how i can get the image and display the image in an imageview.


回答1:


To insert Image on database:

    Bitmap bitmap = ((BitmapDrawable) image_imgv.getDrawable()).getBitmap();

    ByteArrayOutputStream bos4 = new ByteArrayOutputStream();
    bitmap4.compress(Bitmap.CompressFormat.PNG, 100, bos4);
    image = bos4.toByteArray();

    database = new BBDD(this, "BBDD", null, 1);
    SQLiteDatabase db = database.getWritableDatabase();

    ContentValues reg = new ContentValues();
    reg.put("img", image);

To retrieve:

database2 = new BBDD(Activity.this, "BBDD", null, 1);
            SQLiteDatabase db2 = database2.getReadableDatabase();

            if (db2 != null)
            {
                Cursor cursor = db2.rawQuery("SELECT img FROM database2, null);
                if (cursor.moveToFirst())
                {
                    img=cursor.getBlob(cursor.getColumnIndex("img"));
                    Bitmap b1=BitmapFactory.decodeByteArray(image, 0, image.length);
                    image_imageview.setImageBitmap(b1);

                }
                else
                    Toast.makeText(Activity.this, "Error.", Toast.LENGTH_LONG).show();

                db2.close();
            }
            else
                Toast.makeText(sActivity.this, "Error db.", Toast.LENGTH_LONG).show();
        }
    });


来源:https://stackoverflow.com/questions/28630349/how-to-retrieve-an-image-from-a-sqlite-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!