图片在sqlite的保存和读取的学习

一、核心代码

1、bitmap转化为blob格式:
    Bitmap bitmap = data.getExtras().getParcelable("data");
    ByteArrayOutputStream BAOStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, BAOStream);// (0-100)压缩文件
    byte[] Imagebyte = BAOStream.toByteArray();
2、SQLite 中创建blob 数据格式:
    String creatImageSql = "create table ImageDb (" +
         "id   int not null," + 
         "Imagebyte blob," +
         "primary key (CHid) );";
     db.execSQL(creatImageSql);
3、将图片以字节形式存储到数据库
    ContentValues contentValues = new ContentValues();
    contentValues.put(IMAGE, img);
    db.insert( ImageDb, null, contentValues);
4、获取存入数据库的图片,并化为Bitmap形式
    Cursor cursor = select(TB_NAME);
    cursor.moveToPosition(position);
    byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
    Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
5、把Bitmap图片显示在Imageview中
    ImageView imageView; = (ImageView) findViewById(R.id.display_iv);
    imageView.setImageBitmap(bitmap); //把图片显示在ImageView控件上

二、测试demo

1、源代码地址GitHub: https://github.com/fdggfdggyjf/SQLite-/tree/master/chosepicture
2、运行截图;

posted on 2017-12-12 23:07  yejifeng  阅读(1744)  评论(1)    收藏  举报

导航