android 保存图片到数据库

来源:互联网 发布:网上做账软件 编辑:程序博客网 时间:2024/06/04 19:53


方法一:
Java代码 复制代码
  1. public void saveIcon(Bitmap icon) {   
  2.         if (icon == null) {   
  3.             return;   
  4.         }   
  5.   
  6.         // 最终图标要保存到浏览器的内部数据库中,系统程序均保存为SQLite格式,Browser也不例外,因为图片是二进制的所以使用字节数组存储数据库的   
  7.         // BLOB类型   
  8.         final ByteArrayOutputStream os = new ByteArrayOutputStream();   
  9.         // 将Bitmap压缩成PNG编码,质量为100%存储           
  10.         icon.compress(Bitmap.CompressFormat.PNG, 100, os);    
  11.         // 构造SQLite的Content对象,这里也可以使用raw   
  12.         ContentValues values = new ContentValues();    
  13.         // 写入数据库的Browser.BookmarkColumns.TOUCH_ICON字段   
  14.         values.put(Browser.BookmarkColumns.TOUCH_ICON, os.toByteArray());    
  15.            
  16.         DBUtil.update(....);//调用更新或者插入到数据库的方法   
  17.     }  


方法二:如果数据表入口时一个content:URI

 

Java代码 复制代码
  1. import android.provider.MediaStore.Images.Media;   
  2. import android.content.ContentValues;   
  3. import java.io.OutputStream;   
  4.   
  5. // Save the name and description of an image in a ContentValues map.     
  6. ContentValues values = new ContentValues(3);   
  7. values.put(Media.DISPLAY_NAME, "road_trip_1");   
  8. values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");   
  9. values.put(Media.MIME_TYPE, "image/jpeg");   
  10.   
  11. // Add a new record without the bitmap, but with the values just set.   
  12. // insert() returns the URI of the new record.   
  13. Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);   
  14.   
  15. // Now get a handle to the file for that record, and save the data into it.   
  16. // Here, sourceBitmap is a Bitmap object representing the file to save to the database.   
  17. try {   
  18.     OutputStream outStream = getContentResolver().openOutputStream(uri);   
  19.     sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);   
  20.     outStream.close();   
  21. catch (Exception e) {   
  22.     Log.e(TAG, "exception while writing image", e);   
  23. }  
0 0