0

好的,所以下面的代码有效,但我不明白为什么。我正在使用 AVFoundation 从前置摄像头捕获静止图像。在开始捕获之前我有这段代码:

if ([connection isVideoOrientationSupported]) {
    AVCaptureVideoOrientation orientation;

    switch ([UIDevice currentDevice].orientation) {
        case UIDeviceOrientationPortraitUpsideDown:
            orientation = AVCaptureVideoOrientationPortraitUpsideDown;
            break;
        case UIDeviceOrientationLandscapeLeft:
            orientation = AVCaptureVideoOrientationLandscapeRight;
            break;
        case UIDeviceOrientationLandscapeRight:
            orientation = AVCaptureVideoOrientationLandscapeLeft;
            break;
        default:
            orientation = AVCaptureVideoOrientationPortrait;
            break;
    }

    [connection setVideoOrientation:orientation];
}

然后在captureStillImageAsynchronouslyFromConnection:completionHandler:中存储图像:

NSData *imageData = [AVCaptureStillImageOutputjpegStillImageNSDataRepresentation:imageSampleBuffer];
UIImage *i = [UIImage imageWithData:imageData];
orientation:i.imageOrientation];

UIGraphicsBeginImageContext(i.size);

[i drawAtPoint:CGPointMake(0.0, 0.0)];

image.image = UIGraphicsGetImageFromCurrentImageContext();

如您所见,我不旋转图像或任何东西,只是在上下文中绘制并保存。但是一旦我尝试使用i它总是旋转 90 度。如果我尝试使用旋转它

UIImage *rotated = [[UIImage alloc] initWithCGImage:i.CGImage scale:1.0f orientation:i.imageOrientation];

它不起作用(仅使用 没有改变i)。

我知道 UIImage 可能只是使用正确的方向自动将图像绘制到上下文中,但是 WTF?

4

1 回答 1

0

您可以像这样检查设备方向:

 if ((deviceOrientation == UIInterfaceOrientationLandscapeLeft && position ==      AVCaptureDevicePositionBack)
                                                                    )
                                                             {

如果上述条件或您的条件满足,那么您可以使用以下代码旋转您的图像:

-(void)rotateImageByDegress:(int)degrees{
if (degrees == 0.0) {
    return self;
}
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
[rotatedViewBox release];

// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();

// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);

//   // Rotate the image context
CGContextRotateCTM(bitmap, DegreesToRadians(degrees));

// Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;

}

于 2013-09-20T02:46:56.330 回答