zoukankan      html  css  js  c++  java
  • 根据图片Uri获得图片文件

    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表):

  • 相关阅读:
    Bitcode设置 编译问题
    NSDate 时间比较...等
    MagicalRecord 多表关联数据操作
    简单的 同步 异步 请求
    pod创建的工程找不到库
    UITableViewCell 自适应高度 ios8特性
    iOS中nil、Nil、NULL、NSNull详解(转)
    c++ wchar_t 与char 直接的转换【转】
    VS 2010 转到COFF期间失败。
    OpenCV中阈值(threshold)函数: threshold 。
  • 原文地址:https://www.cnblogs.com/wlrhnh/p/3478076.html
Copyright © 2011-2022 走看看