iOS从相册中选择的图片发生旋转的解决办法

现象描述

图片在相册中的显示方向是对的,但是从相册中取出图片然后显示在UIImageView上时图片发生了旋转;

使用下面的取图片方法图片会发生旋转

用下面这段代码取出图片在放到UIImageView上就可能会发生旋转

// 通过ALAsset获取UIImage
- (UIImage *) imageFromALAsset:(ALAsset *)asset
{
    if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
    {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        CGImageRef ref = [rep fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref ];
        return img;
    }
    return nil;
}

// 通过assetURL获取ALAsset
- (void)assetFromURL:(NSURL*)assetsUrl
{
    ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
    [lib assetForURL:assetsUrl resultBlock:^(ALAsset *asset) {
        // _OrientationIV是UIImageView的一个实例
        _OrientationIV.image = [self imageFromALAsset:asset];
    } failureBlock:^(NSError *error) {
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSURL *as = [info objectForKey:UIImagePickerControllerReferenceURL];
    [self assetFromURL:as];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

但是同一张图片用下面的代码获取就不会发生旋转

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    _OrientationIV.image = img;  // _OrientationIV是UIImageView的一个实例
    [picker dismissViewControllerAnimated:YES completion:nil];
}

所以猜测发生旋转的问题可能发生在通过ALAsset获取UIImage这块代码中的下面这一行代码

// 方法一
UIImage *img = [[UIImage alloc]initWithCGImage:ref ];

于是查看API文档,发现还有一个通过CGImage生成UIImage的方法

// 方法二
- (instancetype)initWithCGImage:(CGImageRef)cgImage scale:(CGFloat)scale orientation:(UIImageOrientation)orientation

这个“方法二”比“方法一”多了一个scale参数和一个orientation参数,这里要使用orientation参数来解决问题;

恰好ALAssetRepresentation中有一个获取orientation的方法,只要将orientation做参数传递给“方法二”就可以解决图片旋转的问题,

这里有一个注意点."方法二"中参数的类型是UIImageOrientation类型,而从ALAssetRepresentation中获取的orientationALAssetOrientation类型,所以在使用时要用下面的代码做一下强转

UIImageOrientation orientation = (UIImageOrientation)[rep orientation];

最终正确的代码如下:

- (UIImage *) imageFromALAsset:(ALAsset *)asset
{
    if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
    {
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        CGImageRef ref = [rep fullResolutionImage];
        // 解决图片发生旋转的问题
        UIImageOrientation orientation = (UIImageOrientation)[rep orientation];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref scale:1.0 orientation:orientation];
        return img;
    }
    return nil;
}

知识点

  • imageOrientation

你可能感兴趣的:(iOS从相册中选择的图片发生旋转的解决办法)