调用本地相册选中照片在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 = ; //设置返回代码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, ); 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[]; if ("primary".Equals(type.ToLower()))
{
return Android.OS.Environment.ExternalStorageDirectory + "/" + split[];
} // 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[]; 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[]
}; 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

Xamarin.Android 调用本地相册的更多相关文章

  1. [置顶] Xamarin android 调用Web Api(ListView使用远程数据)

    xamarin android如何调用sqlserver 数据库呢(或者其他的),很多新手都会有这个疑问.xamarin android调用远程数据主要有两种方式: 在Android中保存数据或调用数 ...

  2. Xamarin.Android 调用Web Api(通过ListView展示远程获取的数据)

    xamarin.android如何调用sqlserver 数据库呢(或者其他的),很多新手都会有这个疑问.xamarin.android调用远程数据主要有两种方式: 在Android中保存数据或调用数 ...

  3. Android调用系统相册和拍照的Demo

    最近我在群里看到有好几个人在交流说现在网上的一些Android调用系统相册和拍照的demo都有bug,有问题,没有一个完整的.确实是,我记得一个月前,我一同学也遇到了这样的问题,在低版本的系统中没问题 ...

  4. Android获取本地相册图片、拍照获取图片

    需求:从本地相册找图片,或通过调用系统相机拍照得到图片. 容易出错的地方: 1,当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量 ...

  5. Xamarin.Android 调用手机拍照功能

    最近开发Android遇到了调用本地拍照功能,于是在网上搜了一些方法,加上自己理解的注释,在这儿记录下来省的下次用时候找不到,同事也给正在寻找调用本地拍照功能的小伙伴一些帮助~ 实现思路:首先加载-- ...

  6. Xamarin.Android 调用原生的Jar包

    我们有时候会从Android原生开发(Java)转移到Xamarin.Android开发时,需要将过去写好的Android Class Library直接嵌入到Xamarin.Android底下使用, ...

  7. xamarin.Android 选择本地图片、拍摄图片、剪裁图片

    [Activity(Theme = "@style/MyStyleBottom")] public class SelectPicPopupWindow : Activity, I ...

  8. android 开启本地相册选择图片并返回显示

    .java package com.jerry.crop; import java.io.File; import android.app.Activity; import android.conte ...

  9. Android调用本地WebService

    package com.example.testinvokewebservice; import org.ksoap2.SoapEnvelope; import org.ksoap2.serializ ...

随机推荐

  1. 转)Ubuntu16.04下安装DDD(Data Display Debugger)

    以下转自:http://www.linuxdiyf.com/linux/26393.html   前两天在Linux论坛偶然间看到了DDD这个软件,根据介绍是一个gdb界面化的调试软件,这正是我找了好 ...

  2. iview表格高度自适应只需要三步即可

    1. 需要增加到table表格里的 highlight-row :height="tableHeight" ref="table" 2.在return 定义一个 ...

  3. json-server使用及路由配置

    1.先安装node.js,node.js中包含了json-server模块 2.在angular-hello/src/app/data-base.json文件中,编辑json格式的服务数据, { &q ...

  4. Log4Net web.config配置

     1 .[assembly: log4net.Config.XmlConfigurator(ConfigFile = "web.config", Watch = true)]  写 ...

  5. CITROEN C8 BSI HC12 Mileage Correction with Digiprog3

    CITROEN C8 BSI HC12 odometer correction pinout to Digiprog III Digiprog 3 mileage programmer. The BS ...

  6. 使用GO开发ChainCode

    本来不会GO,最近突击学了些GO的基础,就开始搞chaincode了. 首先给大家推荐一个非常好的Hyperldeger Fabric项目 marble:https://github.com/ibm- ...

  7. delphi三层结构常出现的问题和解决方案

    以下问题出现原因有可能多个,暂时将我遇见的记录下来,以后有新的在陆续更新上去,有网友愿意的话也可以共同测试一下. 一,无法更新定位行.一些值可能已在最后一次读取已更改. 错误出现前提: 1, 录数据时 ...

  8. java8新特性forEach在Map和List的应用

    转自:https://www.cnblogs.com/go-onxp/p/jdk8.html java8 forEach 在Map和List中的使用 原始的使用 Map<String, Inte ...

  9. C#中读写INI文件

    C#中读写INI文件 c#的类没有直接提供对ini文件的操作支持,可以自己包装win api的WritePrivateProfileString和GetPrivateProfileString函数实现 ...

  10. 最长公共子序列(LCS)最长递增子序列(LIS)

    #include<cstring>#include<iostream>#include<stack>#include <algorithm>using ...