Rotate CGImage taken from video frame

╄→尐↘猪︶ㄣ 提交于 2019-11-27 20:34:57

问题


This is Apple's code (from Technical Q&A QA1702) for getting a UIImage from a video buffer. Unfortunately, the image returned is rotated 90 degrees. How do I edit this so that the image returned is correctly oriented?

- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer 
{
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); 
    CVPixelBufferLockBaseAddress(imageBuffer, 0); 

    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); 

    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
    size_t width = CVPixelBufferGetWidth(imageBuffer); 
    size_t height = CVPixelBufferGetHeight(imageBuffer); 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, 
                                                 bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); 

    CGImageRef quartzImage = CGBitmapContextCreateImage(context); 
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);

    CGContextRelease(context); 
    CGColorSpaceRelease(colorSpace);

    UIImage *image = [UIImage imageWithCGImage:quartzImage];

    CGImageRelease(quartzImage);

    return (image);
}

回答1:


Depends on whether you are using the front camera or the back camera

int frontCameraImageOrientation = UIImageOrientationLeftMirrored;
int backCameraImageOrientation = UIImageOrientationRight;

UIImage *image = [[UIImage alloc] initWithCGImage:newImage scale:(CGFloat)1.0 orientation:frontCameraImageOrientation];



回答2:


You can change videoOrientation, this way you get a correct image

connection.videoOrientation = AVCaptureVideoOrientationPortrait

Because by default Video orientation is not portrait.




回答3:


Just rotate the context

Simply rotate the context in radians. This call would rotate the context 90 degrees.

CGFloat degrees = 90.f;
CGFloat radians = degrees * (M_PI / 180.f);
CGContextRotateCTM(context, radians);

You can easily set this method to take the desired orientation and rotate accordingly.



来源:https://stackoverflow.com/questions/4355070/rotate-cgimage-taken-from-video-frame

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