Xamarin.iOS中MediaPicker.CapturePhotoAsync拍照图片旋转问题求助
Xamarin.Essentials MediaPicker 横屏拍照方向处理问题
我正在使用Xamarin.Essentials框架调用相机拍照,使用了MediaPicker.CapturePhotoAsync()方法,代码如下:
async Task CatchPhoto() { var photo = await MediaPicker.CapturePhotoAsync(); if (photo == null) { return; } await LoadPhotoAsync(photo); } async Task LoadPhotoAsync(FileResult photo) { if(photo == null) { PhotoPath = null; return; } var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName); using (var stream = await photo.OpenReadAsync()) using (var newStream = File.OpenWrite(newFile)) await stream.CopyToAsync(newStream); PhotoPath = newFile; UIImage image = UIImage.FromFile(PhotoPath); // 此图片为旋转后的图片 if(image != null) { if(image.Orientation == UIImageOrientation.Up) image = new UIImage(image.CGImage, 1.0f, UIImageOrientation.Right); } }
当前代码在竖屏模式下可正常处理图片方向,但横屏模式下拍照时,上述解决方案失效。请问有什么解决办法?或者有没有其他方法可避免图片旋转?
解决办法
方法1:统一消除图片方向标记依赖
硬编码判断UIImageOrientation.Up仅适配竖屏场景,横屏时可通过绘图上下文生成无方向信息的图片,彻底消除方向标记影响:
修改LoadPhotoAsync中的图片处理逻辑:
async Task LoadPhotoAsync(FileResult photo) { if(photo == null) { PhotoPath = null; return; } var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName); using (var stream = await photo.OpenReadAsync()) using (var newStream = File.OpenWrite(newFile)) await stream.CopyToAsync(newStream); PhotoPath = newFile; UIImage image = UIImage.FromFile(PhotoPath); if(image != null) { UIGraphics.BeginImageContextWithOptions(image.Size, false, image.CurrentScale); image.Draw(CGRect.Empty); var correctedImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); image = correctedImage; } }
方法2:基于EXIF自动修正方向
使用第三方库SixLabors.ImageSharp读取图片EXIF方向标签并自动修正,无需手动判断设备状态:
- 先安装NuGet包
SixLabors.ImageSharp - 修改代码:
using SixLabors.ImageSharp; using SixLabors.ImageSharp.Processing; async Task LoadPhotoAsync(FileResult photo) { if(photo == null) { PhotoPath = null; return; } var newFile = Path.Combine(FileSystem.CacheDirectory, "fixed_" + photo.FileName); using (var stream = await photo.OpenReadAsync()) using (var image = Image.Load(stream)) { image.Mutate(x => x.AutoOrient()); await image.SaveAsync(newFile); } PhotoPath = newFile; UIImage image = UIImage.FromFile(PhotoPath); }
方法3:完善方向判断逻辑
如果不想依赖第三方库,可针对UIImage.Orientation的所有可能值做完整判断,覆盖横屏及其他场景:
if(image != null) { switch(image.Orientation) { case UIImageOrientation.Up: break; case UIImageOrientation.Right: image = new UIImage(image.CGImage, 1.0f, UIImageOrientation.Down); break; case UIImageOrientation.Left: image = new UIImage(image.CGImage, 1.0f, UIImageOrientation.Up); break; case UIImageOrientation.Down: image = new UIImage(image.CGImage, 1.0f, UIImageOrientation.Left); break; default: image = new UIImage(image.CGImage, 1.0f, UIImageOrientation.Up); break; } }
内容的提问来源于stack exchange,提问作者Swati
相关产品推荐
相关产品推荐

