加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将图片存储到Sqlite和取出

发布时间:2020-12-12 19:41:24 所属栏目:百科 来源:网络整理
导读://第一步,将Drawable对象转化为Bitmap对象 Bitmapbmp=(((BitmapDrawable)tmp.image).getBitmap()); //第二步,声明并创建一个输出字节流对象 ByteArrayOutputStreamos=newByteArrayOutputStream(); //第三步,调用compress将Bitmap对象压缩为PNG格式,第二
//第一步,将Drawable对象转化为Bitmap对象

Bitmapbmp=(((BitmapDrawable)tmp.image).getBitmap());

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

ByteArrayOutputStreamos=newByteArrayOutputStream();

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

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

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

ContentValuesvalues=newContentValues();

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,blob.length);


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


BitmapDrawable bd = new BitmapDrawable(bmp);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读