打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Bitmap Drawable byte[] 三者之间的转换以及把数组存入数据库及提取数据重新组合成所需对象

1.创建数据库表的时候选择存图片的字段类型为blob

StringBuffer createTableOfHistory = newStringBuffer();
createTableOfHistory.append("CREATE TABLE "+某表名);
createTableOfHistory.append(" ( _id INTEGER PRIMARY KEY AUTOINCREMENT ,");
createTableOfHistory.append(该存图片的字段名+" BLOB ,");
createTableOfHistory.append(其他字段名1+" TEXT ,");
.......
createTableOfHistory.append(其他字段名n+" TEXT );");//记得这里带个“;”封号
db.execSQL(createTableOfHistory.toString());//执行该创表语句

2.存储数据

2.1将数据流转成数组的方法

InputStream inputStream = getResources().openRawResource(R.drawable.icon);
privatestaticbyte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = newByteArrayOutputStream(1024);
byte[] buffer = newbyte[1024];
intlen;
try{
while((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch(java.io.IOException e) {
}
returnos.toByteArray();
}

2.2.将Bitmap对象转换成数组的方法【包含从资源文件中获得图片对象Bitmap】

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
privatestaticbyte[] bitmapToBytes(Bitmap bitmap){
if(bitmap == null) {
returnnull;
}
finalByteArrayOutputStream os = newByteArrayOutputStream();
// 将Bitmap压缩成PNG编码,质量为100%存储
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);//除了PNG还有很多常见格式,如jpeg等。
returnos.toByteArray();
}
ContentValues values = newContentValues();
values.put(该存图片的字段名, readHistoryInfo.getBookIcon());
values.put(其他字段名1, “2011-05-17”);
......
returnmSqliteDatabase.insert(表名, null, values);//插入数据

3.提取数据库中的数组数据并转换成Bitmap或DrawableBitmap对象【包含byte[] —> Bitmap】

某类对象m(该类是负责创表,删表,插入数据,删除数据的类).openOrCreateDB();//openOrCreateDB()也是该类的一个打开或创建数据库的方法。

Cursor cursor = 某类对象m.getData(该存图片的字段名, null);
if(cursor.moveToFirst()) {
// byte[] —> Bitmap
byte[] bytes = cursor.getBlob(cursor.getColumnIndex(该存图片的字段名));
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
BitmapDrawable bitmapDrawable = newBitmapDrawable(bitmap);
}

4.Drawable —> Bitmap

Bitmap bm = xxx; //xxx根据你的情况获取
BitmapDrawable bd= newBitmapDrawable(bm);
提示:因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
publicstaticBitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ?
Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);
returnbitmap;
}
Drawable d=xxx; //xxx根据自己的情况获取drawable
BitmapDrawable bd = (BitmapDrawable) d;
Bitmap bm = bd.getBitmap();
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Drawable、Bitmap、byte[]之间的转换问题
Bitmap和Drawable相互转换方法
Android中屏幕Density对BitmapDrawable的影响
实现Android图片圆角
Android Bitmap和Canvas笔记
android Bitmap学习总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服