iOS 11.0 之后拍照生成的imageOrientation的问题 |
您所在的位置:网站首页 › ios拍照翻转 › iOS 11.0 之后拍照生成的imageOrientation的问题 |
背景 使用AVCapturePhotoCaptureDelegate在iOS 11之后生成图片,直接转data,然后生成的图片的imageOrientation方向始终不正确,后面有对图片旋转的需求时,如果根据imageOrientation来操作,就一直不正确。 通俗点是,拍照的时候,横屏拍照的图片,想要显示的时候转成竖屏,如果在回掉的地方不处理,那么后续根据图片的方向来处理是行不通的。 调试获取AVCapturePhoto的NSData,然后根据NSData生成图片AVCapturePhotoCaptureDelegate回掉方法,在某个StackOverFlow的回答中,这么使用,直接从AVCapturePhoto 生成ImageData,然后生成image,如下;这时候调试会发现,image的imageOrientation始终是UIImageOrientationRight。 这个方法生成的图片,最后的表现就是怎么拍的图片怎么显示。 代码语言:javascript复制- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)){ if (!error) { NSData *imageData = [photo fileDataRepresentation]; UIImage * image = [self imageDirection:imageData]; [self takeImageCompletion:tempImage buffer:nil error:error]; } }获取AVCapturePhoto的CGImageRef,然后生成图片,如下这时候调试会发现,image的imageOrientation始终是UIImageOrientationUp。 代码语言:javascript复制- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)){ if (!error) { CGImageRef ref = [photo CGImageRepresentation]; UIImage * image = [UIImage imageWithCGImage:ref]; [self takeImageCompletion:tempImage buffer:nil error:error]; } }那么如果想要实现,生成image的imageOrientation是正确的,要怎么处理呢?有人会说,从AVCapturePhoto的metadata中获取kCGImagePropertyOrientation字段,然后根据这个字段的方向,生成图片,比如How to generate an UIImage from AVCapturePhoto with correct orientation? 但是笔者尝试了一下,这时候笔者这边获取到的值仍旧是一个固定的值,并没有因为设备拍照方向的不同而改变然后就只剩下最后一个方法,根据设备的方向,根据设备的方向,生成图片对应的imageOrientation,然后再合成图片。这时候需要注意是按照拍照时的设备方向,还是生成时的设备方向,需要使用者自己抉择,演示如下,这时候不管怎么拍的图片,最终显示都会变成竖屏的显示了代码语言:javascript复制- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error API_AVAILABLE(ios(11.0)){ if (!error) { CGImageRef ref = [photo CGImageRepresentation]; // 这里是用的是生成图片时的设备方向,如果需要按照拍照时的设备方向,可以在capureOutput:willCapturePhotoForResolvedSettings:中保存 UIImageOrientation orientation = [self getUIImageOrientationFromDevice]; UIImage *tempImage = [UIImage imageWithCGImage:ref scale:1.0 orientation:orientation]; [self takeImageCompletion:tempImage buffer:nil error:error]; } } // 这个方法可以放在UIDeviceOrientation的Category中统一定义 - (UIImageOrientation)getUIImageOrientationFromDevice { UIDeviceOrientation orientation = [UIDevice currentDevice].orientation; switch (orientation) { case UIDeviceOrientationPortrait: case UIDeviceOrientationFaceUp: return UIImageOrientationRight; break; case UIDeviceOrientationPortraitUpsideDown: case UIDeviceOrientationFaceDown: return UIImageOrientationLeft; case UIDeviceOrientationLandscapeLeft: return UIImageOrientationUp; case UIDeviceOrientationLandscapeRight: return UIImageOrientationDown; default: return UIImageOrientationUp; break; } } |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |