Xamarin 表单:如何从图库或相机选择图片后实现图像裁剪

2024-01-21

我在用媒体插件 https://github.com/jamesmontemagno/MediaPlugin用于打开相机和图库来选择图片。选择图片后,我需要在将其设置到 UI 之前对其进行裁剪。我努力了AllowCropping = true在相机中,但它仅适用于 Windows 和 ios。对于 Android 中的相机和所有平台(Android、iOS 和 Windows)上的图库,没有裁剪选项。

I tried ImageCropper.Forms https://github.com/stormlion227/ImageCropper.Forms包来实现图像裁剪功能。

My Code:

//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.Abstractions.IMedia.TakePhotoAsync(Plugin.Media.Abstractions.StoreCameraMediaOptions ) 在 System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine] (TStateMachine& stateMachine) [0x0002c] 在 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/系统/运行时/compilerservices/AsyncMethodBuilder.cs:84 在Stormlion.ImageCropper.ImageCropper.Show(Xamarin.Forms.Page页面,System.String imageFile)[0x00033]在:0 在 F:\My Projects\Xamarin\ProjectName\ProjectName\ProjectName\Pages\ProfilePage.xaml.cs 中的 ProjectName.Pages.ProfilePage.GalleryClick () [0x00227]:554

[0:]异常:> System.MissingMethodException:找不到方法:System.Threading.Tasks.Task`1 Plugin.Media.Abstractions.IMedia.TakePhotoAsync(Plugin.Media.Abstractions.StoreCameraMediaOptions ) 在 System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine] (TStateMachine& stateMachine) [0x0002c] 在 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/系统/运行时/compilerservices/AsyncMethodBuilder.cs:84 在Stormlion.ImageCropper.ImageCropper.Show(Xamarin.Forms.Page页面,System.String imageFile)[0x00033]在:0 在 F:\My Projects\Xamarin\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>

另外,您不需要调用CrossMedia.Current.PickPhotoAsync,只需像下面的代码一样直接执行ImageCropper即可。

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);
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Xamarin 表单:如何从图库或相机选择图片后实现图像裁剪 的相关文章

随机推荐