UIImagePickerController拍照的UIImag

作者: 极客飞 | 来源:发表于2018-12-26 11:00 被阅读5次
问题呈现
调用系统UIImagePickerController拍照,竖着拍照,然后获取UIImage原图,上传到服务器发现,图片逆时针旋转了90度,很奇怪。如下图。 正常竖版图.jpg 问题图.jpg
获取返回的UIImage
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
分析过程

拍照返回的image 在UIImageView 上显示,方向没有问题,保存到相册中,也没有问题。但是将image写到沙盒目录下,就会出现上图的问题,如果把这个图上传给服务器,后台看到的图片就不正常。
首先,将image写到沙盒目录的时候,对image没有做任何修改,这一步肯定没问题。那就是image本身的问题,发现image有个imageOrientation的只读属性,对应的UIImageOrientation是枚举类型,如下:

typedef NS_ENUM(NSInteger, UIImageOrientation) {
    UIImageOrientationUp,            // default orientation
    UIImageOrientationDown,          // 180 deg rotation
    UIImageOrientationLeft,          // 90 deg CCW
    UIImageOrientationRight,         // 90 deg CW
    UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
    UIImageOrientationDownMirrored,  // horizontal flip
    UIImageOrientationLeftMirrored,  // vertical flip
    UIImageOrientationRightMirrored, // vertical flip
};
打印输出image.imageOrientation,找出问题
NSLog(@"%ld",(long)image.imageOrientation);

打印输出image.imageOrientation,发现,横向拍照获取的imageOrientation输出0,通过枚举来看应该是UIImageOrientationUp,但是竖着拍照获取的imageOrientation输出是3,通过枚举来看应该是UIImageOrientationRight,那这应该就是问题所在了。竖着拍照返回来的image的方向默认就是已经逆时针旋转了90度,我们在往沙盒写入之前就需要将image调整过来。

解决问题
if(image.imageOrientation!=UIImageOrientationUp){
            // Adjust picture Angle
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }

获取到image之后通过上边方法可实现将不正确的imageOrientation调整过来。这个坑,找了好久才找出来。至于为什么UIImageView显示和保存在相册里没问题就不清楚了。

相关文章

网友评论

    本文标题:UIImagePickerController拍照的UIImag

    本文链接:https://www.haomeiwen.com/subject/akqqlqtx.html