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 表单:如何从图库或相机选择图片后实现图像裁剪 的相关文章

  • Android 中拍摄的照片方向发生变化

    我通过单击按钮打开相机应用程序 并在下一个活动中显示捕获的照片 但拍摄的照片旋转了90度 当我捕获图像后在视图中显示图像时 它的方向始终是横向的 为什么在纵向模式下拍摄照片时 照片显示的不是纵向 onClick 按钮 Intent i ne
  • iOS 更新到 15 后列表视图顶部出现奇怪的空间

    我在用着 Xamarin Froms 5 0 0 24125 Xcode 版本 13 0 13A233 Visual Studio for Mac 社区版本 8 10 9 内部版本 3 NuGet版本 5 9 0 7134 Xamarin
  • Xamarin.Forms:独立于平台的应用程序菜单

    我正在编写 Xamarin Forms 桌面应用程序 最终希望以 MacOS 和 Windows 为目标 Xamarin Forms 是否有任何独立于平台的机制可用于构建应用程序菜单 即您可以在其中找到 文件 编辑 查看 等的菜单 并且出现
  • 设置使用 iPhone 相机拍摄的图像的类型

    如果我们使用 iPhone 相机拍摄照片 图像将默认以 JPEG 格式保存 我想以其他格式 例如 PNG 保存捕获的图像 是否可以 当我们从应用程序调用 iPhone 相机时 是否可以通过代码执行此操作 我们可以设置捕获图片后必须保存的图像
  • 带 Prism 的表单:应用程序窗口预计有一个根 VC

    我刚刚在我的新应用程序中实现了 Prism 库 并且正在使用 NavigationService 它在 Android 上运行良好 但是当我尝试在联网的 Mac 上调试我的 Xamarin Forms iOS 应用程序时 我的 Main 方
  • 如何将屏幕截图转换为二进制?

    我正在开发一个 Xamarin Forms 项目 在该项目中我想将我的屏幕截图 PNG 转换为二进制并将其上传到服务器 现在服务器部分需要一个API 我将由已经完成它的人交给我 我只需要实现它 在我完成这个任务之后 到目前为止 我已经成功地
  • 如何将代码 AVFoundation Objective C 转换为 Swift?

    我正在 swift 中使用 AVFoundation 来拍照 但我无法将任何 func 代码行从 Objective C 转换为 Swift 我的功能代码是 void capImage method to capture image fro
  • 启动注册期间无法加载程序集“System.Buffers”

    我的 Xamarin 表单应用程序大约 5 分钟前运行 然后突然停止工作 应用程序启动后立即关闭 下面显示了 Visual Studio 输出中的消息显示 Assembly Loader probing location System Bu
  • Xamarin Forms 自定义地图图钉

    在我正在开发的应用程序之一中 我需要使用自定义地图图钉 并且我已遵循 Xamarin 上的指南https developer xamarin com guides xamarin forms application fundamentals
  • 从 2 个摄像头捕获(OpenCV、Python)[重复]

    这个问题在这里已经有答案了 所以我试图从 openCV 中的两个摄像头 python 和 windows 7 进行捕获 我用一台相机拍摄的效果很好 你也会注意到我正在对图像做一些时髦的事情 但这并不重要 这是尝试使用两个的代码 import
  • Xamarin 表单:jamesmontemagno/MediaPlugin:添加到 IOS 应用程序中的 UI 时,所选图片会旋转

    我跟着this https github com jamesmontemagno MediaPlugin用于从画廊和相机拍摄照片的博客 但在 IOS 的 UI 中 所选图片以右旋转形式显示 仅在使用相机时才会出现问题 而我对图库没有任何问题
  • 如何在Android模拟器相机中模拟图片?

    有没有办法将模拟器相机拍摄的照片设置为静态图片 我想在模拟器上使用 zxing 条形码阅读器测试 ir 如果您在 Linux 上运行模拟器 您可以使用 v4l2loopback 和 gstreamer 创建一个显示图像 例如 QRcode
  • 如何在 unity3d C# 中让相机跟随物体?

    我有一个名为 Ball 的对象 我向它添加了键盘交互性 WASD 来移动球 我需要摄像机留在后面并跟随球 但我遇到了错误 using UnityEngine using System Collections public class bal
  • Xamarin.Forms 绘图[关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在为客户构建一个 Xamarin Forms 项目 我们需要一个图形库它将处理实时流式传输的数据连
  • Camera.Parameters.FLASH_MODE_ON 在 Moto X 上不起作用

    我正在 moto x 上测试我的应用程序 即使打开闪光灯模式后 闪光灯也无法工作 应用程序在其他设备上运行良好 但在 Moto X 上运行不佳 这是一个代码片段 cameraInstance getCameraInstance camera
  • Camera.open()返回NULL Android开发

    我正在按照构建相机应用程序的教程进行操作http developer android com tools device html http developer android com tools device html我对 Camera o
  • Android 相机未保存在特定文件夹 [MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA]

    当我在 Intent 中使用 MediaStore INTENT ACTION STILL IMAGE CAMERA 时遇到问题 相机正常启动 但它不会将文件保存在我的特定文件夹 photo 中 但是当我使用 MediaStore ACTI
  • 如何在 Android 中保存相机的临时照片?

    在尝试从相机拍照并将其保存到应用程序的缓存文件夹中时 我没有得到任何可见的结果 应用程序不会崩溃 但在 LogCat 上 当我尝试将 ImageView src 字段设置为刚刚获取的文件的 URI 时 我收到此消息 09 17 14 03
  • 汉堡菜单棱镜xamarin形式?

    我正在尝试在 Xamarin Forms 中使用 Prism 创建一个应用程序 Xamarin 表单版本 2 3 3 175 棱镜版本 6 2 0 汉堡菜单可以在 Android 中使用 但是当我在 UWP 上运行它时 它不会显示图标 而且
  • 没有支持 FEATURE_CAMERA_EXTERNAL 的 Android 设备

    根据this doc https source android com devices camera external usb cameras一些 Android 设备允许使用 Camera2 API 访问外部 USB 摄像头 我检查了大约

随机推荐