Xamarin.forms Xamarin表单:如何在从gallery或camera中选择图片后实现图像裁剪

Xamarin.forms Xamarin表单:如何在从gallery或camera中选择图片后实现图像裁剪,xamarin.forms,camera,gallery,Xamarin.forms,Camera,Gallery,我正在使用打开相机和图库来选择图片。选择图片后,我需要在UI上设置它之前对其进行裁剪。我在相机中尝试过AllowCropping=true,但它只适用于windows和ios。对于所有平台(android、ios和windows)上的android和gallery中的摄像头,没有裁剪选项 我试着用软件包实现图像裁剪功能 我的代码: //Camera async void CameraClick() { try { await CrossMedia.Current.

我正在使用打开相机和图库来选择图片。选择图片后,我需要在UI上设置它之前对其进行裁剪。我在相机中尝试过
AllowCropping=true
,但它只适用于windows和ios。对于所有平台(android、ios和windows)上的android和gallery中的摄像头,没有裁剪选项

我试着用软件包实现图像裁剪功能

我的代码:

//Camera
async void CameraClick()
{
    try
    {
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            if (!Utility.IsWindowsDevice())
            {
                await DisplayAlert("Alert", "No camera available.", "Ok");
            }
            else
            {
                ShowAlert("No camera available.");
            }
            return;
        }

        _mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            Directory = "Sample",
            Name = "test.jpg",
            AllowCropping = true,
            PhotoSize = PhotoSize.Medium
        });

        if (_mediaFile == null)
            return;
        profilephoto.Source = ImageSource.FromStream(() =>
        {
            isPicture = true;
            isAvatar = false;
            if (Device.OS == TargetPlatform.iOS)
            {
                return _mediaFile.GetStreamWithImageRotatedForExternalStorage();
            }
            else
            {
                return _mediaFile.GetStream();
            }
        });

        new ImageCropper()
        {
            PageTitle = "Test Title",
            AspectRatioX = 1,
            AspectRatioY = 1,
            CropShape = ImageCropper.CropShapeType.Rectangle,
            SelectSourceTitle = "Select source",
            TakePhotoTitle = "Take Photo",
            PhotoLibraryTitle = "Photo Library",
            Success = (imageFile) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    profilephoto.Source = ImageSource.FromFile(imageFile);
                });
            }
        }.Show(this);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
    }
}

//Gallery
async void GalleryClick()
{
    try
    {
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsPickPhotoSupported)
        {
            if (!Utility.IsWindowsDevice())
            {
                await DisplayAlert("Alert", "No photos available.", "Ok");
            }
            else
            {
                ShowAlert("No photos available.");
            }
            return;
        }

        _mediaFile = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
        {
            PhotoSize = PhotoSize.Medium
        });

        if (_mediaFile == null)
            return;
        profilephoto.Source = ImageSource.FromStream(() =>
        {
            isPicture = true;
            isAvatar = false;
            return _mediaFile.GetStream();
        });

        new ImageCropper()
        {
            PageTitle = "Test Title",
            AspectRatioX = 1,
            AspectRatioY = 1,
            CropShape = ImageCropper.CropShapeType.Rectangle,
            SelectSourceTitle = "Select source",
            TakePhotoTitle = "Take Photo",
            PhotoLibraryTitle = "Photo Library",
            Success = (imageFile) =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    profilephoto.Source = ImageSource.FromFile(imageFile);
                });
            }
        }.Show(this);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
    }
}
我已经按照博客做了所有的事情,但是当我运行时得到了下面的例外

[0:]异常:>System.MissingMethodException:未找到方法:System.Threading.Tasks.Task`1 Plugin.Media.Abstracts.IMedia.TakePhotoAsync(Plugin.Media.Abstracts.StoreCameramedOptions) 在/Users/builder/jenkins/workspace/archive mono/2020-02/android/release/mcs/class/referencesource/mscorlib/System/Runtime/CompilerServices/asynchmethodbuilder.cs:84中启动[TStateMachine](TStateMachine&stateMachine)[0x0002c 在:0中的Stormlion.ImageCropper.ImageCropper.Show(Xamarin.Forms.Page页面,System.String imageFile)[0x00033]处 在ProjectName.Pages.ProfilePage.GalleryClick()[0x00227]中的F:\My Projects\Xamarin\ProjectName\ProjectName\ProjectName\Pages\ProfilePage.xaml.cs:554

[0:]异常:>System.MissingMethodException:未找到方法:System.Threading.Tasks.Task`1 Plugin.Media.Abstracts.IMedia.TakePhotoAsync(Plugin.Media.Abstracts.StoreCameramedOptions) 在/Users/builder/jenkins/workspace/archive mono/2020-02/android/release/mcs/class/referencesource/mscorlib/System/Runtime/CompilerServices/asynchmethodbuilder.cs:84中启动[TStateMachine](TStateMachine&stateMachine)[0x0002c 在:0中的Stormlion.ImageCropper.ImageCropper.Show(Xamarin.Forms.Page页面,System.String imageFile)[0x00033]处 在F:\My Projects\Xamarin\ProjectName\ProjectName\ProjectName\ProjectName\Pages\ProfilePage.xaml.cs中的ProjectName.Pages.ProfilePage.CameraClick()[0x0025b]处:515 01-20 12:21:23.149 D/Mono(11820):请求加载System.Collections.dll的参考1(共3个)


不知道这背后的问题是什么。是否有其他简单的软件包来实现图像裁剪功能?

首先,将ImageCropper.Forms.Fix.v2nuget软件包添加到您的项目中

然后,如果您使用
AndroidX
,请更改AndroidManifest.xaml标记中的代码

<application android:label="ImageCropDemo.Android" android:theme="@style/MainTheme">
    <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
              android:theme="@style/Base.Theme.AppCompat"/>
    <provider android:name="androidx.core.content.FileProvider"
          android:authorities="${applicationId}.fileprovider"
          android:exported="false"
          android:grantUriPermissions="true">
      <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
                       android:resource="@xml/file_paths"></meta-data>
    </provider>
    </application>

不使用ImageCropper.Forms软件包是否有效?您可以共享您的示例,这样我就可以对其进行测试。@LucasZhang MSFT我将准备示例并尽快与您共享。您可以在mainpage.xaml.cs中添加完整的代码吗?发布它。当使用插件ImageCropper时,您不需要再使用MediaPlugin,因为ImageCropper已经包含了它。但是您仍然需要安装并初始化MediaPlugin。OnClickedRectangle是一个按钮单击事件。是否可以将最终图像值设置为MediaFile?因为我需要将所选图像发布到服务器,如下所示:“content.Add(newstreamcontent(\u mediaFile.GetStream()),“\”file\”,$“\”{u mediaFile.Path}\”;”目前我使用了{u mediaFile.GetStream()和{u mediaFile.Path值。
namespace ImageCropDemo
{
    public partial class MainPage : ContentPage
    {
        private MediaFile _mediaFile;
        public MainPage()
        {
            InitializeComponent();

 

            CrossMedia.Current.Initialize();

 

        }
        protected  void OnClickedRectangle(object sender, EventArgs e)
        {
            new ImageCropper()
            {
                //                PageTitle = "Test Title",
                //                AspectRatioX = 1,
                //                AspectRatioY = 1,
                Success = (imageFile) =>
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        image.Source = ImageSource.FromFile(imageFile);
                    });
                }
            }.Show(this);
        }
        async void OpenCamera(object sender, EventArgs args)
        {
            try
            {
                await CrossMedia.Current.Initialize();

 

                //if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                //{
                //    await DisplayAlert("Alert", "No camera available.", "Ok");
                //    return;
                //}

 

                //_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                //{
                //    Directory = "Sample",
                //    Name = "test.jpg",
                //    AllowCropping = true,
                //    PhotoSize = PhotoSize.Medium
                //});

 

                //if (_mediaFile == null)
                //    return;
                //image.Source = ImageSource.FromStream(() =>
                //{
                //    if (Device.OS == TargetPlatform.iOS)
                //    {
                //        return _mediaFile.GetStreamWithImageRotatedForExternalStorage();
                //    }
                //    else
                //    {
                //        return _mediaFile.GetStream();
                //    }
                //});

 

                new ImageCropper()
                {
                    PageTitle = "Test Title",
                    AspectRatioX = 1,
                    AspectRatioY = 1,
                    CropShape = ImageCropper.CropShapeType.Rectangle,
                    SelectSourceTitle = "Select source",
                    TakePhotoTitle = "Take Photo",
                    PhotoLibraryTitle = "Photo Library",
                    Success = (imageFile) =>
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            image.Source = ImageSource.FromFile(imageFile);
                        });
                    }
                }.Show(this);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("CameraException:>" + ex);
            }
        }
        string imagefile;
        async void OpenGallery(object sender, EventArgs args)
        {
            try
            {
                await CrossMedia.Current.Initialize();

 

                //if (!CrossMedia.Current.IsPickPhotoSupported)
                //{
                //    await DisplayAlert("Alert", "No photos available.", "Ok");
                //    return;
                //}

 

                //_mediaFile = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
                //{
                //    PhotoSize = PhotoSize.Medium
                //});

 

                //if (_mediaFile == null)
                //    return;

 

                //image.Source = ImageSource.FromStream(() =>
                //{
                //    return _mediaFile.GetStream();
                //});

 

                new ImageCropper()
                {
                    PageTitle = "Test Title",
                    AspectRatioX = 1,
                    AspectRatioY = 1,
                    CropShape = ImageCropper.CropShapeType.Rectangle,
                    SelectSourceTitle = "Select source",
                    TakePhotoTitle = "Take Photo",
                    PhotoLibraryTitle = "Photo Library",
                    Success = (imageFile) =>
                    {
                        Device.BeginInvokeOnMainThread (() =>
                        {
                            image.Source = ImageSource.FromFile(imageFile);

 

                            imagefile = imageFile;
                        });
                    }
                }.Show(this);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("GalleryException:>" + ex);
            }
        }
    }
}