Подтвердить что ты не робот

Ориентация камеры iPhone AVFoundation

Я рвал волосы, пытаясь заставить камеру AVFoundation захватить изображение в правильной ориентации (то есть ориентацию устройства), но я не могу заставить его работать.

Я посмотрел учебники, я смотрел презентацию WWDC, и я загрузил пробную программу WWDC, но даже это не делает.

Код из моего приложения...

AVCaptureConnection *videoConnection = [CameraVC connectionWithMediaType:AVMediaTypeVideo fromConnections:[imageCaptureOutput connections]];
if ([videoConnection isVideoOrientationSupported])
{
    [videoConnection setVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
}

[imageCaptureOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
    if (imageDataSampleBuffer != NULL)
    {
        //NSLog(@"%d", screenOrientation);

        //CMSetAttachment(imageDataSampleBuffer, kCGImagePropertyOrientation, [NSString stringWithFormat:@"%d", screenOrientation], 0);

        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [[UIImage alloc] initWithData:imageData];

        [self processImage:image];
    }
}];

(processImage использует тот же метод writeImage... как код WWDC)

и код из приложения WWDC...

AVCaptureConnection *videoConnection = [AVCamDemoCaptureManager connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
        if ([videoConnection isVideoOrientationSupported]) {
            [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        }

[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
                                                             completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
                                                                 if (imageDataSampleBuffer != NULL) {
                                                                     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                                     UIImage *image = [[UIImage alloc] initWithData:imageData];                                                                 
                                                                     ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
                                                                     [library writeImageToSavedPhotosAlbum:[image CGImage]
                                                                                               orientation:(ALAssetOrientation)[image imageOrientation]
                                                                                           completionBlock:^(NSURL *assetURL, NSError *error){
                                                                                               if (error) {
                                                                                                   id delegate = [self delegate];
                                                                                                   if ([delegate respondsToSelector:@selector(captureStillImageFailedWithError:)]) {
                                                                                                       [delegate captureStillImageFailedWithError:error];
                                                                                                   }                                                                                               
                                                                                               }
                                                                                           }];
                                                                     [library release];
                                                                     [image release];
                                                                 } else if (error) {
                                                                     id delegate = [self delegate];
                                                                     if ([delegate respondsToSelector:@selector(captureStillImageFailedWithError:)]) {
                                                                         [delegate captureStillImageFailedWithError:error];
                                                                     }
                                                                 }
                                                             }];

В начале кода они устанавливают AVOrientation на портрет, который кажется очень странным, но я пытаюсь заставить его определить текущую ориентацию устройства и использовать его.

Как вы можете видеть, я поставил [UIApplication sharedApplication] statusBarOrientation, чтобы попытаться получить это, но он сохраняет только фотографии в портрете.

Может ли кто-нибудь предложить какую-либо помощь или совет относительно того, что мне нужно делать?

Спасибо!

Оливер

4b9b3361

Ответ 1

Ну, это заставило меня трахаться вечно, но я это сделал!

Бит кода, который я искал,

[UIDevice currentDevice].orientation;

Это происходит так

AVCaptureConnection *videoConnection = [CameraVC connectionWithMediaType:AVMediaTypeVideo fromConnections:[imageCaptureOutput connections]];
if ([videoConnection isVideoOrientationSupported])
{
    [videoConnection setVideoOrientation:[UIDevice currentDevice].orientation];
}

И он отлично работает: D

Woop woop!

Ответ 2

Разве это немного чище?

    AVCaptureVideoOrientation newOrientation;
    switch ([[UIDevice currentDevice] orientation]) {
    case UIDeviceOrientationPortrait:
        newOrientation = AVCaptureVideoOrientationPortrait;
        break;
    case UIDeviceOrientationPortraitUpsideDown:
        newOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
        break;
    case UIDeviceOrientationLandscapeLeft:
        newOrientation = AVCaptureVideoOrientationLandscapeRight;
        break;
    case UIDeviceOrientationLandscapeRight:
        newOrientation = AVCaptureVideoOrientationLandscapeLeft;
        break;
    default:
        newOrientation = AVCaptureVideoOrientationPortrait;
    }
    [stillConnection setVideoOrientation: newOrientation];

Ответ 3

В AVCam сказано следующее:

- (void)deviceOrientationDidChange{

    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];

    AVCaptureVideoOrientation newOrientation;

    if (deviceOrientation == UIDeviceOrientationPortrait){
        NSLog(@"deviceOrientationDidChange - Portrait");
        newOrientation = AVCaptureVideoOrientationPortrait;
    }
    else if (deviceOrientation == UIDeviceOrientationPortraitUpsideDown){
        NSLog(@"deviceOrientationDidChange - UpsideDown");
        newOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
    }

    // AVCapture and UIDevice have opposite meanings for landscape left and right (AVCapture orientation is the same as UIInterfaceOrientation)
    else if (deviceOrientation == UIDeviceOrientationLandscapeLeft){
        NSLog(@"deviceOrientationDidChange - LandscapeLeft");
        newOrientation = AVCaptureVideoOrientationLandscapeRight;
    }
    else if (deviceOrientation == UIDeviceOrientationLandscapeRight){
        NSLog(@"deviceOrientationDidChange - LandscapeRight");
        newOrientation = AVCaptureVideoOrientationLandscapeLeft;
    }

    else if (deviceOrientation == UIDeviceOrientationUnknown){
        NSLog(@"deviceOrientationDidChange - Unknown ");
        newOrientation = AVCaptureVideoOrientationPortrait;
    }

    else{
        NSLog(@"deviceOrientationDidChange - Face Up or Down");
        newOrientation = AVCaptureVideoOrientationPortrait;
    }

    [self setOrientation:newOrientation];
}

И обязательно добавьте это в свой метод init:

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[notificationCenter addObserver:self
    selector:@selector(deviceOrientationDidChange) 
    name:UIDeviceOrientationDidChangeNotification object:nil];
[self setOrientation:AVCaptureVideoOrientationPortrait];

Ответ 4

есть две вещи, которые можно заметить

a), как писал Брайан Кинг - LandscapeRight и LandscapeLeft меняются местами в перечислении. пример AVCamCaptureManager:

// AVCapture and UIDevice have opposite meanings for landscape left and right (AVCapture orientation is the same as UIInterfaceOrientation)
else if (deviceOrientation == UIDeviceOrientationLandscapeLeft)
    orientation = AVCaptureVideoOrientationLandscapeRight;
else if (deviceOrientation == UIDeviceOrientationLandscapeRight)
    orientation = AVCaptureVideoOrientationLandscapeLeft;

b) Есть также UIDeviceOrientationFaceUp и UIDeviceOrientationFaceDown, что если вы попытаетесь установить ориентацию видео, ваше видео не будет записываться. Убедитесь, что вы не используете их при вызове [UIDevice currentDevice].orientation!

Ответ 5

Если вы используете AVCaptureVideoPreviewLayer, вы можете сделать следующее внутри своего контроллера представления.

(при условии, что у вас есть экземпляр AVCaptureVideoPreviewLayer, называемый "previewLayer" )

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   [self.previewLayer setOrientation:[[UIDevice currentDevice] orientation]];
}

Ответ 6

Я пишу этот код в Swift в случае, если это может понадобиться кому-то.

Шаг-1: генерировать уведомления о ориентации (в viewDidLoad)

    UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("deviceOrientationDidChange:"), name: UIDeviceOrientationDidChangeNotification, object: nil)

Шаг-2: Сделайте снимок. Здесь мы будем обменивать ориентацию videoConnection. В AVFoundation происходит незначительное изменение ориентации, особенно для ландшафтной ориентации. Поэтому мы просто заменим его. Например, мы изменим с LandscapeRight на LandscapeLeft и наоборот

  func takePicture() {
if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {

    var newOrientation: AVCaptureVideoOrientation?
    switch (UIDevice.currentDevice().orientation) {
    case .Portrait:
        newOrientation = .Portrait
        break
    case .PortraitUpsideDown:
        newOrientation = .PortraitUpsideDown
        break
    case .LandscapeLeft:
        newOrientation = .LandscapeRight
        break
    case .LandscapeRight:
        newOrientation = .LandscapeLeft
        break
    default :
        newOrientation = .Portrait
        break

    }
    videoConnection.videoOrientation = newOrientation!


  stillImageOutput!.captureStillImageAsynchronouslyFromConnection(videoConnection) {
    (imageDataSampleBuffer, error) -> Void in

    let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {

      dispatch_async(dispatch_get_main_queue()) {

        let image = UIImage(data: imageData!)!
        let portraitImage = image.fixOrientation()


      }
    }


  }
}

  }

ПРИМЕЧАНИЕ. Обратите внимание на новое значение ориентации для ориентации ландшафта. Это как раз наоборот. (Это преступник:: UHHHH)

Шаг 3: ориентация фиксации (расширение UIImage)

extension UIImage {

func fixOrientation() -> UIImage {

    if imageOrientation == UIImageOrientation.Up {
        return self
    }

    var transform: CGAffineTransform = CGAffineTransformIdentity

    switch imageOrientation {
    case UIImageOrientation.Down, UIImageOrientation.DownMirrored:
        transform = CGAffineTransformTranslate(transform, size.width, size.height)
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
        break
    case UIImageOrientation.Left, UIImageOrientation.LeftMirrored:
        transform = CGAffineTransformTranslate(transform, size.width, 0)
        transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
        break
    case UIImageOrientation.Right, UIImageOrientation.RightMirrored:
        transform = CGAffineTransformTranslate(transform, 0, size.height)
        transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
        break
    case UIImageOrientation.Up, UIImageOrientation.UpMirrored:
        break
    }

    switch imageOrientation {
    case UIImageOrientation.UpMirrored, UIImageOrientation.DownMirrored:
        CGAffineTransformTranslate(transform, size.width, 0)
        CGAffineTransformScale(transform, -1, 1)
        break
    case UIImageOrientation.LeftMirrored, UIImageOrientation.RightMirrored:
        CGAffineTransformTranslate(transform, size.height, 0)
        CGAffineTransformScale(transform, -1, 1)
    case UIImageOrientation.Up, UIImageOrientation.Down, UIImageOrientation.Left, UIImageOrientation.Right:
        break
    }

    let ctx: CGContextRef = CGBitmapContextCreate(nil, Int(size.width), Int(size.height), CGImageGetBitsPerComponent(CGImage), 0, CGImageGetColorSpace(CGImage), CGImageAlphaInfo.PremultipliedLast.rawValue)!

    CGContextConcatCTM(ctx, transform)

    switch imageOrientation {
    case UIImageOrientation.Left, UIImageOrientation.LeftMirrored, UIImageOrientation.Right, UIImageOrientation.RightMirrored:
        CGContextDrawImage(ctx, CGRectMake(0, 0, size.height, size.width), CGImage)
        break
    default:
        CGContextDrawImage(ctx, CGRectMake(0, 0, size.width, size.height), CGImage)
        break
    }

    let cgImage: CGImageRef = CGBitmapContextCreateImage(ctx)!

    return UIImage(CGImage: cgImage)
}


   }

Ответ 7

Это использует метод ориентации контроллера вида. Это работает для меня, надеюсь, работает для вас.

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

    AVCaptureConnection *videoConnection = self.prevLayer.connection;
    [videoConnection setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
}

Ответ 8

В Swift вы должны сделать это:

    videoOutput = AVCaptureVideoDataOutput()
    videoOutput!.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL))

    if captureSession!.canAddOutput(self.videoOutput) {
        captureSession!.addOutput(self.videoOutput)
    }

    videoOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown

Он отлично работает для меня!

Ответ 9

Вы также можете создать промежуточный CIImage и захватить словарь свойств

NSDictionary *propDict = [aCIImage properties];
NSString *orientString = [propDict objectForKey:kCGImagePropertyOrientation];

И преобразуйте соответственно:)

Мне нравится, как легко получить доступ ко всем этим метаданным изображения в iOS5!

Ответ 10

Обновите ориентацию в слое предварительного просмотра после начала сеанса захвата и всякий раз, когда устройство поворачивается.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { [weak self] context in
        if let connection = self?.previewLayer?.connection, connection.isVideoOrientationSupported {
            if let orientation = AVCaptureVideoOrientation(orientation: UIDevice.current.orientation) {
                connection.videoOrientation = orientation
            }
        }
    }, completion: nil)
    super.viewWillTransition(to: size, with: coordinator)
}

extension AVCaptureVideoOrientation {
    init?(orientation: UIDeviceOrientation) {
        switch orientation {
        case .landscapeRight: self = .landscapeLeft
        case .landscapeLeft: self = .landscapeRight
        case .portrait: self = .portrait
        case .portraitUpsideDown: self = .portraitUpsideDown
        default: return nil
        }
    }
}

Ответ 11

Как использовать с AVCaptureFileOutput?

- (void)detectVideoOrientation:(AVCaptureFileOutput *)captureOutput {
    for(int i = 0; i < [[captureOutput connections] count]; i++) {
        AVCaptureConnection *captureConnection = [[captureOutput connections] objectAtIndex:i];
        if([captureConnection isVideoOrientationSupported]) {
            [captureConnection setVideoOrientation:[[UIDevice currentDevice] orientation]];
        }
    }
}