将图片存储到Sqlite和取出

  //第一步,将Drawable对象转化为Bitmap对象

Bitmap bmp = (((BitmapDrawable)tmp.image).getBitmap());

//第二步,声明并创建一个输出字节流对象

ByteArrayOutputStream os = new ByteArrayOutputStream();

//第三步,调用compress将Bitmap对象压缩为PNG格式,第二个参数为PNG图片质量,第三个参数为接收容器,即输出字节流os

bmp.compress(Bitmap.CompressFormat.PNG, 100, os);

//第四步,将输出字节流转换为字节数组,并直接进行存储数据库操作,注意,所对应的列的数据类型应该是BLOB类型

ContentValues values = new ContentValues();

values.put("image", os.toByteArray());

db.insert("apps", null, values);

db.close(); 

         代码看起来比较繁琐,是因为过程的确挺繁琐的,不过可以简单的总结为:

        Drawable→Bitmap→ByteArrayOutputStream→SQLite

        二、读取 
 //第一步,从数据库中读取出相应数据,并保存在字节数组中


byte[] blob = cursor.getBlob(cursor.getColumnIndex("image"));


//第二步,调用BitmapFactory的解码方法decodeByteArray把字节数组转换为Bitmap对象


Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);


//第三步,调用BitmapDrawable构造函数生成一个BitmapDrawable对象,该对象继承Drawable对象,所以在需要处直 接使用该对象即可


BitmapDrawable bd = new BitmapDrawable(bmp);


        很显然,读取是存储的相反过程,代码思路也差不多,但实现起来简单很多,总结思路为:

        SQLite→byte[]→Bitmap→BitmapDrawable 


  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值