原理:图片是二进制文件,所以使用blob类型,将图片转换成字节数组,存储到数据库中。

方法一:

1.public void saveIcon(Bitmap icon) {
2. if (icon == null) {

3. return; 4.

}
5. // 最终图标要保存到浏览器的内部数据库中,系统程序均保存为SQLite格式,Browser也不例外,因为图片是二进制的所以使用字节数组存储数据库的

6. // BLOB类型

7. final ByteArrayOutputStream os = new ByteArrayOutputStream();

8. // 将Bitmap压缩成PNG编码,质量为100%存储

9. icon.compress(Bitmap.CompressFormat.PNG, 100, os);

10. // 构造SQLite的Content对象,这里也可以使用raw

11. ContentValues values = new ContentValues();

12. // 写入数据库的Browser.BookmarkColumns.TOUCH_ICON字段

13. values.put(Browser.BookmarkColumns.TOUCH_ICON, os.toByteArray());
14.
15. DBUtil.update(....);//调用更新或者插入到数据库的方法 16. }

方法二:

1.import Android.provider.MediaStore.Images.Media;
2.import Android.content.ContentValues;

3.import java.io.OutputStream;

4.// Save the name and description of an image in a ContentValues map.

5.ContentValues values = new ContentValues(3);

6.values.put(Media.DISPLAY_NAME, "road_trip_1");

7.values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");

8.values.put(Media.MIME_TYPE, "image/jpeg");

9.// Add a new record without the bitmap, but with the values just set.

10.// insert() returns the URI of the new record.

11.Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
12.// Now get a handle to the file for that record, and save the data into it.

13.// Here, sourceBitmap is a Bitmap object representing the file to save to the database.

14.try {

15. OutputStream outStream = getContentResolver().openOutputStream(uri);
16. sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);

17. outStream.close();
18.} catch (Exception e) {

19. Log.e(TAG, "exception while writing image", e); 20.}

从数据库中读取:

1.byte[] blob = cur.getBlob(cur.getColumnIndex(KEY_IMG));
2.Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);

本篇文章来源于 Linux公社网站(www.linuxidc.com) 原文链接:http://www.linuxidc.com/Linux/2011-07/39106.htm

更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. Android官方提供的支持不同屏幕大小的全部方法
  3. 关于 Android(安卓)下的自动化测试方法介绍
  4. Android(安卓)Retrofit + RxJava使用详解
  5. Android解决UnsupportedOperationException异常!
  6. 游戏音频-详解MediaPlayer,SoundPool利弊
  7. activity的启动过程分析
  8. Android(安卓)Manager之MediaRecorder(音视频录制)
  9. Andorid入门--HTTP数据传输和WebView的使用

随机推荐

  1. Android 屏幕旋转后防止重新执行onCreate
  2. Activity或者FragmenitActivity锁屏后会
  3. android 中Java和javascript的交互
  4. Android(安卓)事件监听
  5. 解决在sdk manager中更新文件后出现This
  6. Android基于XMPP Smack openfire 开发的
  7. 26、android上跑apache的ftp服务
  8. Android(安卓)代码用来返回上一个activit
  9. android底层开发入门(3)-Android Driver前
  10. php服务端与android客户端socket通信