Xamarin.Android 调用本地相册

简介:   调用本地相册选中照片在ImageView上显示代码:using System;using System.Collections.Generic;using System.Linq;using System.

  调用本地相册选中照片在ImageView上显示

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Provider;
using Android.Database;
using System.Threading;
using Java.IO;

namespace CallLocalPhoto
{
    [Activity(Label = "CallLocalPhoto", MainLauncher = true)]
    public class MainActivity : Activity
    {
        Button btn;
        ImageView iv;

        private Java.IO.File originalFile;
        private const int PhotoGallery_RequestCode = 1;     //设置返回代码Code,可自行定义
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
            originalFile = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(
                Android.OS.Environment.DirectoryPictures
                ), "zcb_pic_" + SystemClock.CurrentThreadTimeMillis() + ".png");

            btn = FindViewById<Button>(Resource.Id.button1);
            iv = FindViewById<ImageView>(Resource.Id.imageView1);
            btn.Click += Btn_Click;
        }

        private void Btn_Click(object sender, EventArgs e)
        {
            CutImageByImgStore();
        }

        /// <summary>
        /// 调用相册选择
        /// </summary>
        private void CutImageByImgStore()
        {
            Intent _intentCut = new Intent(Intent.ActionGetContent, null);
            _intentCut.SetType("image/*");// 设置文件类型
            _intentCut.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(originalFile));
            _intentCut.PutExtra(MediaStore.ExtraVideoQuality, 1);

            StartActivityForResult(_intentCut, PhotoGallery_RequestCode);
        }

        /// <summary>
        /// 选择图片后返回
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="ResultStatus"></param>
        /// <param name="data"></param>
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result ResultStatus, Intent data)
        {
            if (ResultStatus == Result.Ok)
            {
                /*
                * 若系统版本低于4.4,返回原uri
                * 若高于4.4,解析uri后返回
                * */
                if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                {
                    var url = Android.Net.Uri.Parse("file://" + GetPath(BaseContext, data.Data));
                    data.SetData(url);

                    //将本地相册照片显示在控件上
                    iv.SetImageURI(Android.Net.Uri.FromFile(new File(GetPath(BaseContext, data.Data))));
                }
            }
        }

        #region 高于 v4.4 版本 解析真实路径


        public static String GetPath(Context context, Android.Net.Uri uri)
        {

            bool isKitKat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            // DocumentProvider  
            if (isKitKat && DocumentsContract.IsDocumentUri(context, uri))
            {
                // ExternalStorageProvider  
                if (isExternalStorageDocument(uri))
                {
                    String docId = DocumentsContract.GetDocumentId(uri);
                    String[] split = docId.Split(':');
                    String type = split[0];

                    if ("primary".Equals(type.ToLower()))
                    {
                        return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1];
                    }

                    // TODO handle non-primary volumes  
                }
                // DownloadsProvider  
                else if (isDownloadsDocument(uri))
                {

                    String id = DocumentsContract.GetDocumentId(uri);
                    Android.Net.Uri contentUri = ContentUris.WithAppendedId(
                            Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider  
                else if (isMediaDocument(uri))
                {
                    String docId = DocumentsContract.GetDocumentId(uri);
                    String[] split = docId.Split(':');
                    String type = split[0];

                    Android.Net.Uri contentUri = null;
                    if ("image".Equals(type))
                    {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if ("video".Equals(type))
                    {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if ("audio".Equals(type))
                    {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }

                    String selection = "_id=?";
                    String[] selectionArgs = new String[] {
                    split[1]
            };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)  
            else if ("content".Equals(uri.Scheme.ToLower()))
            {

                // Return the remote address  
                if (isGooglePhotosUri(uri))
                    return uri.LastPathSegment;

                return getDataColumn(context, uri, null, null);
            }
            // File  
            else if ("file".Equals(uri.Scheme.ToLower()))
            {
                return uri.Path;
            }

            return null;
        }

        /** 
         * Get the value of the data column for this Uri. This is useful for 
         * MediaStore Uris, and other file-based ContentProviders. 
         * 
         * @param context The context. 
         * @param uri The Uri to query. 
         * @param selection (Optional) Filter used in the query. 
         * @param selectionArgs (Optional) Selection arguments used in the query. 
         * @return The value of the _data column, which is typically a file path. 
         */
        public static String getDataColumn(Context context, Android.Net.Uri uri, String selection,
                String[] selectionArgs)
        {

            ICursor cursor = null;
            String column = "_data";
            String[] projection = {
                column
            };

            try
            {
                cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs,
                        null);
                if (cursor != null && cursor.MoveToFirst())
                {
                    int index = cursor.GetColumnIndexOrThrow(column);
                    return cursor.GetString(index);
                }
            }
            finally
            {
                if (cursor != null)
                    cursor.Close();
            }
            return null;
        }


        /** 
         * @param uri The Uri to check. 
         * @return Whether the Uri authority is ExternalStorageProvider. 
         */
        public static bool isExternalStorageDocument(Android.Net.Uri uri)
        {
            return "com.android.externalstorage.documents".Equals(uri.Authority);
        }

        /** 
         * @param uri The Uri to check. 
         * @return Whether the Uri authority is DownloadsProvider. 
         */
        public static bool isDownloadsDocument(Android.Net.Uri uri)
        {
            return "com.android.providers.downloads.documents".Equals(uri.Authority);
        }

        /** 
         * @param uri The Uri to check. 
         * @return Whether the Uri authority is MediaProvider. 
         */
        public static bool isMediaDocument(Android.Net.Uri uri)
        {
            return "com.android.providers.media.documents".Equals(uri.Authority);
        }

        /** 
         * @param uri The Uri to check. 
         * @return Whether the Uri authority is Google Photos. 
         */
        public static bool isGooglePhotosUri(Android.Net.Uri uri)
        {
            return "com.google.android.apps.photos.content".Equals(uri.Authority);
        }

        #endregion
    }
}

 

下载地址:

  链接: https://pan.baidu.com/s/1Yhlv2oHsAH-9Hs8WolX7Lw

  密码: h6g7

目录
相关文章
|
6月前
|
Android开发
Android调用相机与相册的方法1
Android调用相机与相册的方法
81 0
|
6月前
|
XML Java Android开发
Android Studio App开发之使用相机拍摄照片和从相册中选取图片(附源码 超详细必看)
Android Studio App开发之使用相机拍摄照片和从相册中选取图片(附源码 超详细必看)
820 0
|
Android开发
Android中实现获取相册中的图片扫描二维码的功能
Android中实现获取相册中的图片扫描二维码的功能
266 0
|
6月前
|
Android开发
Android保存图片到相册(适配android 10以下及以上)
Android保存图片到相册(适配android 10以下及以上)
134 1
|
6月前
|
Android开发
Android调用相机与相册的方法2
Android调用相机与相册的方法
68 0
|
Java Android开发
Android 保存资源图片到相册最新写法适用于Android10.0及以上
Android 保存资源图片到相册最新写法适用于Android10.0及以上
825 0
|
SQL 数据库 Android开发
Android 访问系统相册选中图片,并返回该图片的路径
Android 访问系统相册选中图片,并返回该图片的路径
204 0
|
Android开发
Android获取相册中图片的路径 4.4版本前后的变化
Android获取相册中图片的路径 4.4版本前后的变化
181 0
|
6月前
|
XML vr&ar Android开发
【Android App】实战项目之虚拟现实(VR)的全景相册(附源码和演示视频 可用于学习和大作业)
【Android App】实战项目之虚拟现实(VR)的全景相册(附源码和演示视频 可用于学习和大作业)
321 2
|
Android开发
Android -- 相册图片发送彩信
Android -- 相册图片发送彩信
111 0