Android(安卓)保存图片到Sqlite数据库
16lz
2021-01-24
转自http://www.linuxidc.com/Linux/2011-07/39106.htm
- publicvoidsaveIcon(Bitmapicon){
- if(icon==null){
- return;
- }
- //最终图标要保存到浏览器的内部数据库中,系统程序均保存为SQLite格式,Browser也不例外,因为图片是二进制的所以使用字节数组存储数据库的
- //BLOB类型
- finalByteArrayOutputStreamos=newByteArrayOutputStream();
- //将Bitmap压缩成PNG编码,质量为100%存储
- icon.compress(Bitmap.CompressFormat.PNG,100,os);
- //构造SQLite的Content对象,这里也可以使用raw
- ContentValuesvalues=newContentValues();
- //写入数据库的Browser.BookmarkColumns.TOUCH_ICON字段
- values.put(Browser.BookmarkColumns.TOUCH_ICON,os.toByteArray());
- DBUtil.update(....);//调用更新或者插入到数据库的方法
- }
方法二:
- importAndroid.provider.MediaStore.Images.Media;
- importandroid.content.ContentValues;
- importjava.io.OutputStream;
- //SavethenameanddescriptionofanimageinaContentValuesmap.
- ContentValuesvalues=newContentValues(3);
- values.put(Media.DISPLAY_NAME,"road_trip_1");
- values.put(Media.DESCRIPTION,"Day1,triptoLosAngeles");
- values.put(Media.MIME_TYPE,"image/jpeg");
- //Addanewrecordwithoutthebitmap,butwiththevaluesjustset.
- //insert()returnstheURIofthenewrecord.
- Uriuri=getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,values);
- //Nowgetahandletothefileforthatrecord,andsavethedataintoit.
- //Here,sourceBitmapisaBitmapobjectrepresentingthefiletosavetothedatabase.
- try{
- OutputStreamoutStream=getContentResolver().openOutputStream(uri);
- sourceBitmap.compress(Bitmap.CompressFormat.JPEG,50,outStream);
- outStream.close();
- }catch(Exceptione){
- Log.e(TAG,"exceptionwhilewritingimage",e);
- }
从数据库中读取:
- byte[]blob=cur.getBlob(cur.getColumnIndex(KEY_IMG));
- Bitmapbmp=BitmapFactory.decodeByteArray(blob,0,blob.length);
更多相关文章
- Android(安卓)4.0.1_r1源代码发布,更新获取方法
- Android全屏(包含3种隐藏顶部状态栏及标题栏和一种隐藏Android(安
- Android中JNI高级应用 - 本地C代码中创建Java对象及本地JNI对象
- 动态权限
- android中获取string字符串的方法
- Android屏幕100%适配方案
- java.lang.IllegalStateException Fragment already added: Home
- android软件盘的开关
- Android面试-Android部分