2013-12-17

1. 根据联系人图片Uri获得图片文件并将它显示在ImageView上, 代码如下:

 1 Uri uri = Uri.parse("content://com.android.contacts/display_photo/1");
 2     AssetFileDescriptor afd;
 3     try {
 4         afd = getContentResolver().openAssetFileDescriptor(uri, "r");
 5         byte[] buffer = new byte[16 * 1024];
 6         FileInputStream fis = afd.createInputStream();
 7         // 保存为图片
 8         FileOutputStream fos = new FileOutputStream(new File("sdcard/11212"));
 9         // 将byte array存储到ByteArrayOutputStream
10         ByteArrayOutputStream temp_byte = new ByteArrayOutputStream();
11         int size;
12         while ((size = fis.read(buffer)) != -1) {
13             fos.write(buffer, 0, size);
14             temp_byte.write(buffer, 0, size);
15         }
16         // 获得图片资源并设置给ImageView
17         image.setImageBitmap(BitmapFactory.decodeByteArray(temp_byte.toByteArray(), 0, temp_byte.size()));
18     } catch (FileNotFoundException e) {
19         e.printStackTrace();
20     } catch (IOException e) {
21         e.printStackTrace();
22     }

上面可以看到, uri就是联系人数据库view_data视图里面的photo_uri字段,最后的id要根据实际情况调整。

2. 根据mediaURI获取资源的存储路径

 1 Cursor cur = getContentResolver().query(Uri.parse("content://media/external/images/media/279"), null, null, null, null);
 2 if (cur != null) {
 3     for (int i = 0; i < cur.getColumnCount(); i++) {
 4          Log.d("Davds", "name = " + cur.getColumnName(i));
 5     }
 6        
 7     while (cur.moveToNext()) {
 8          Log.d("Davds", "" + cur.getString(cur.getColumnIndex("_data")));
 9     }
10 }

从_data对应的filed中取出来的值就是文件的存储路径。

数据库中显示如下(在MediaProvider数据库中images表):

 

 posted on 2013-12-17 11:14  wlrhnh  阅读(3533)  评论(1编辑  收藏  举报