how to store Image as blob in Sqlite & how to retrieve it?

后端 未结 6 943
野的像风
野的像风 2020-11-22 04:31

I want to store an image(from url) into a sqlite database.

For that I use:

db = new DataBase(getApplicationContext());
URL url = new URL(\"http://sr         


        
6条回答
  •  广开言路
    2020-11-22 05:01

    in the DBAdaper i.e Data Base helper class declare the table like this

     private static final String USERDETAILS=
        "create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";
    

    insert the values like this,

    first convert the images as byte[]

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);   
    byte[] photo = baos.toByteArray(); 
    db.insertUserDetails(value1,value2, value3, photo,value2);
    

    in DEAdaper class

     public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("username", uname);
        initialValues.put("userid",userid);
        initialValues.put("password", pass);
        initialValues.put("photo",photo);
        initialValues.put("visibility",visibility);
        return db.insert("userdetails", null, initialValues);
    }
    

    retrieve the image as follows

    Cursor cur=your query;
    while(cur.moveToNext())
    {
         byte[] photo=cur.getBlob(index of blob cloumn);
    }
    

    convert the byte[] into image

    ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
    Bitmap theImage= BitmapFactory.decodeStream(imageStream);
    

    I think this content may solve your problem

提交回复
热议问题