Xamarin 调用手机相册及摄像头代码

代码:

Plugin.Media.Abstractions.MediaFile mediaFile = null;
var action = string.Empty;
try
{
    action = await CoreMethods.DisplayActionSheet("请选择一种方式上传", "取消", null, "拍照", "相册");
    if (action == "相册")
    {
        if (await CheckPhotoPermisson())
        {
            await Task.Yield();
            mediaFile = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
            {
                PhotoSize = PhotoSize.Large,
                CompressionQuality = 100,
                CustomPhotoSize = 100,
            });//选相册
        }
    }
    if (action == "拍照")
    {
        if (await CheckCameraPermisson())
        {
            await Task.Yield();
            var storeCameraMediaOptions = new StoreCameraMediaOptions
            {
                AllowCropping = true,
                DefaultCamera = CameraDevice.Rear,
                SaveToAlbum = false,
                PhotoSize = PhotoSize.Large,
            };
            mediaFile = await CrossMedia.Current.TakePhotoAsync(storeCameraMediaOptions);//拍照 
        }
    }
    byte[] headByte = null;
    //压缩处理
    if (mediaFile != null)
    {
        headByte = ResizeImage(mediaFile);//压缩图像的方法
    }
    //判空退出
    if (headByte != null)
    {
        Stream stream = new MemoryStream(headByte);
        MyImageSource = ImageSource.FromStream(() => stream);
    }
}
catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex.ToString());
}

效果


第一次需要设置权限



这里通过数据绑定将MyImageSource与页面控件进行绑定,这样就显示选中的图片了。


没有更多推荐了,返回首页