web-dev-qa-db-ja.com

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はWWDCコードと同じwriteImage ...メソッドを使用します)

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を設定して取得しようとしましたが、写真は縦向きでしか保存されません。

誰かが私がしなければならないことについて何か助けやアドバイスを提供できますか?

ありがとう!

オリバー

35
Fogmeister

まあ、それは私を永遠にフラッキングしましたが、私はそれをやった!

私が探していたコードのビットは

[UIDevice currentDevice].orientation;

これはそのままです

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

そしてそれは完全に動作します:D

やったー!

45
Fogmeister

これは少しきれいではありませんか?

    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];
14
Bill Cheswick

以下は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];
11
W Dyson

注意すべき点が2つあります

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)UIDeviceOrientationFaceUpUIDeviceOrientationFaceDownの状態もあり、ビデオの向きとして設定しようとすると、ビデオの記録に失敗します。 [UIDevice currentDevice].orientationを呼び出すときは、これらを使用しないでください。

4
iRadium

AVCaptureVideoPreviewLayerを使用している場合は、ビューコントローラ内で次の操作を実行できます。

(「previewLayer」と呼ばれるAVCaptureVideoPreviewLayerのインスタンスがあると仮定します)

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

キャプチャセッションの開始後、デバイスが回転するたびにプレビューレイヤーの方向を更新します。

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
        }
    }
}
2
rockdaswift

私はこのコードをSwiftで書いています。

ステップ-1:オリエンテーション通知を生成する(your 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)
}


   }
2
Abdul Yasin

これは、ビューコントローラーの方向メソッドを使用します。これでうまくいきます。うまくいけばうまくいきます。

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

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

Swift 4&Swift 5。

さあ行こう:

private var requests = [VNRequest]()
let exifOrientation = exifOrientationFromDeviceOrientation()
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:])
do {
  try imageRequestHandler.perform(self.requests)
} catch {
  print(error)
}

public func exifOrientationFromDeviceOrientation() -> CGImagePropertyOrientation {
    let curDeviceOrientation = UIDevice.current.orientation
    let exifOrientation: CGImagePropertyOrientation

    switch curDeviceOrientation {
    case UIDeviceOrientation.portraitUpsideDown:  // Device oriented vertically, home button on the top
        exifOrientation = .upMirrored
    case UIDeviceOrientation.landscapeLeft:       // Device oriented horizontally, home button on the right
        exifOrientation = .left
    case UIDeviceOrientation.landscapeRight:      // Device oriented horizontally, home button on the left
        exifOrientation = .right
    case UIDeviceOrientation.portrait:            // Device oriented vertically, home button on the bottom
        exifOrientation = .up
    default:
        exifOrientation = .up
    }
    return exifOrientation
}
1
Dary

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

それは私にとって完璧に機能します!

1
vkalit

中間CIImageを作成し、プロパティディクショナリを取得することもできます

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

そしてそれに応じて変換:)

IOS5でこのすべての画像メタデータに簡単にアクセスできるのが気に入っています。

0
johntraver