这是Apple的代码(来自Technical Q& A QA1702),用于从视频缓冲区获取UIImage。不幸的是,返回的图像旋转了90度。如何编辑它以使返回的图像正确定向?
- (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);
}
答案 0 :(得分:25)
取决于您使用的是前置摄像头还是后置摄像头
int frontCameraImageOrientation = UIImageOrientationLeftMirrored;
int backCameraImageOrientation = UIImageOrientationRight;
UIImage *image = [[UIImage alloc] initWithCGImage:newImage scale:(CGFloat)1.0 orientation:frontCameraImageOrientation];
答案 1 :(得分:3)
您可以更改videoOrientation,这样您就可以获得正确的图像
connection.videoOrientation = AVCaptureVideoOrientationPortrait
因为默认情况下,视频方向不是肖像。
答案 2 :(得分:2)
只需以弧度旋转上下文即可。此调用会将上下文旋转90度。
CGFloat degrees = 90.f;
CGFloat radians = degrees * (M_PI / 180.f);
CGContextRotateCTM(context, radians);
您可以轻松设置此方法以获得所需的方向并相应地旋转。