iOS:背对着相机照片倒置,正面朝上的照片正好向上

时间:2016-01-21 11:00:46

标签: ios objective-c camera photo avcapturesession

我的iPad应用只能用于横向方向。在感觉我看了几十个堆栈答案之后,我无法正确地拍摄照片(元数据更正了它,但仅在mac上有用)。当应用程序实际位于LandscapeLeft时,它会返回一张颠倒的照片,而在LandscapeRight中,它是正确的。

据我所知,为预览图层设置VideoOrientation可以在预览照片时为我提供正确的方向。

_capturePreview = [[ISCapturePreview alloc] init];
    [self addSubview:_capturePreview];

    // Session
    self.session = [AVCaptureSession new];
    [self.session setSessionPreset:AVCaptureSessionPresetPhoto];

    // Capture device
    AVCaptureDevice* inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error;

    // Device input
    self.deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
    if ( [self.session canAddInput:self.deviceInput] )
        [self.session addInput:self.deviceInput];

    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

    // Preview
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [previewLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
    [previewLayer.connection setVideoOrientation:(AVCaptureVideoOrientation)orientation];
    [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    CALayer *rootLayer = [[self capturePreview] layer];
    [rootLayer setMasksToBounds:YES];
    [previewLayer setFrame:CGRectMake(0, 0, 1024, 600)];
    [rootLayer insertSublayer:previewLayer atIndex:0];

    AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    if ([self.session canAddOutput:stillImageOutput])
    {
        [stillImageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
        [self.session addOutput:stillImageOutput];
        [self setStillImageOutput:stillImageOutput];
    }

    [self.session startRunning];

输出代码在这里。在我的测试中设置VideoOrientation没有任何影响。

    - (void)takePhotoButtonWasPressed:(id)sender{
[[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self capturePreview] layer] connection] videoOrientation]];

// Capture a still image.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

    if (imageDataSampleBuffer)
    {
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [[UIImage alloc] initWithData:imageData];
}];}

1 个答案:

答案 0 :(得分:0)

我目前无法自行测试代码,但如果您将可用的方向(在项目设置中)设置为landscapeLeft和landscapeRight,iOS可能会处理方向本身,因此请尝试不设置方向。此外,如果在加载视图后更改设备的方向,则将使用错误的方向,因此请考虑添加观察者以检查更改。另外,apple说你应该从iOS8开始使用UITraitCollectionUITraitEnvironment而不是UIInterfaceOrientation

我希望这可以帮助你:)