根据图片Uri获得图片文件

时间:2022-01-26 06:44:13

2013-12-17

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

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

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

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

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

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

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

根据图片Uri获得图片文件