AVAssetImageGenerator provides images rotated

a 夏天 提交于 2019-12-17 17:47:09

问题


When obtaining a UIImage of a video via AVAssetImageGenerator, I'm getting back images rotated (well, technically they're not) when the video is shot in portrait orientation. How can I tell what orientation the video was shot and then rotate the image properly?

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
NSError *err = NULL;
CMTime time = CMTimeMake(0, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
[generate release];
UIImage *currentImg = [[UIImage alloc] initWithCGImage:imgRef];

回答1:


The easiest way is to just set the appliesPreferredTrackTransform property on the image generator to YES, then it should automatically do the transformation for you.




回答2:


The copy and paste solution to create image with the recording orientation using the previous answer.

AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
AVAssetImageGenerator* imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil];
UIImage* image = [UIImage imageWithCGImage:cgImage];

CGImageRelease(cgImage);



回答3:


Here is the solution in swift version 4:

func thumbnailImageForFileUrl(_ fileUrl: URL) -> UIImage? {
    let asset = AVAsset(url: fileUrl)
    let imageGenerator = AVAssetImageGenerator(asset: asset)
    imageGenerator.appliesPreferredTrackTransform = true

    do {

        let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(1, 60), actualTime: nil)
        return UIImage(cgImage: thumbnailCGImage)

    } catch let err {
        print(err)
    }

    return nil
}


来源:https://stackoverflow.com/questions/5347800/avassetimagegenerator-provides-images-rotated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!