从AVCaptureSession捕获iPhone图像比率

时间:2012-01-10 08:15:49

标签: iphone camera uiimage avcapturesession

我正在使用某人的源代码来使用AVCaptureSession捕获图像。但是,我发现CaptureSessionManager的previewLayer是最终捕获的图像,然后是enter image description here

我发现生成的图像总是比率为720x1280 = 9:16。现在我想将结果图像裁剪为比例为320:480的UIImage,以便它只捕获previewLayer中可见的部分。任何的想法?非常感谢。

stackoverflow中的相关问题(还没有很好的答案): Q1Q2

源代码:

- (id)init {
if ((self = [super init])) {
    [self setCaptureSession:[[[AVCaptureSession alloc] init] autorelease]];
}
return self;
}

- (void)addVideoPreviewLayer {
[self setPreviewLayer:[[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]] autorelease]];
[[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill];

}

- (void)addVideoInput {
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];   
if (videoDevice) {
    NSError *error;


    if ([videoDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus] && [videoDevice lockForConfiguration:&error]) {
        [videoDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
        [videoDevice unlockForConfiguration];
    }        

    AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    if (!error) {
        if ([[self captureSession] canAddInput:videoIn])
            [[self captureSession] addInput:videoIn];
        else
            NSLog(@"Couldn't add video input");     
    }
    else
        NSLog(@"Couldn't create video input");
}
else
    NSLog(@"Couldn't create video capture device");
}

- (void)addStillImageOutput 
{
  [self setStillImageOutput:[[[AVCaptureStillImageOutput alloc] init] autorelease]];
  NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
  [[self stillImageOutput] setOutputSettings:outputSettings];

  AVCaptureConnection *videoConnection = nil;
  for (AVCaptureConnection *connection in [[self stillImageOutput] connections]) {
    for (AVCaptureInputPort *port in [connection inputPorts]) {
      if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
        videoConnection = connection;
        break;
      }
    }
    if (videoConnection) { 
      break; 
    }
  }

  [[self captureSession] addOutput:[self stillImageOutput]];
}

- (void)captureStillImage
{  
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in [[self stillImageOutput] connections]) {
    for (AVCaptureInputPort *port in [connection inputPorts]) {
        if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
            videoConnection = connection;
            break;
        }
    }
    if (videoConnection) { 
  break; 
}
}

NSLog(@"about to request a capture from: %@", [self stillImageOutput]);
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection 
                                                   completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) { 
                                                     CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
                                                     if (exifAttachments) {
                                                       NSLog(@"attachements: %@", exifAttachments);
                                                     } else { 
                                                       NSLog(@"no attachments");
                                                     }
                                                     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];    
                                                     UIImage *image = [[UIImage alloc] initWithData:imageData];
                                                     [self setStillImage:image];
                                                     [image release];
                                                     [[NSNotificationCenter defaultCenter] postNotificationName:kImageCapturedSuccessfully object:nil];
                                                   }];
}


进行更多研究和测试后编辑: AVCaptureSession的属性“sessionPreset”具有以下常量,我没有检查过它们中的每一个,但是注意到它们中的大多数比例是9:16或3:4,

  • NSString * const AVCaptureSessionPresetPhoto;
  • NSString * const AVCaptureSessionPresetHigh;
  • NSString * const AVCaptureSessionPresetMedium;
  • NSString * const AVCaptureSessionPresetLow;
  • NSString * const AVCaptureSessionPreset352x288;
  • NSString * const AVCaptureSessionPreset640x480;
  • NSString * const AVCaptureSessionPresetiFrame960x540;
  • NSString * const AVCaptureSessionPreset1280x720;
  • NSString * const AVCaptureSessionPresetiFrame1280x720;

在我的项目中,我有全屏预览(帧大小为320x480) 还有:[[self previewLayer] setVideoGravity:AVLayerVideoGravityResizeAspectFill];

我已经这样做了:拍摄尺寸为9:16的照片并将其裁剪为320:480,这正是预览层的可见部分。它看起来很完美。

用于调整大小和裁剪以替换旧代码的代码是

NSData *imageData = [AVCaptureStillImageOutput  jpegStillImageNSDataRepresentation:imageSampleBuffer];
 UIImage *image = [UIImage imageWithData:imageData]; 
UIImage *scaledimage=[ImageHelper scaleAndRotateImage:image];
 //going to crop the image 9:16 to 2:3;with Width fixed 
float width=scaledimage.size.width; 
float height=scaledimage.size.height; 
float top_adjust=(height-width*3/2.0)/2.0;  
[self setStillImage:[scaledimage croppedImage:rectToCrop]];

1 个答案:

答案 0 :(得分:36)

iPhone的相机本身就是4:3。你得到的16:9图像已经从4:3裁剪掉了。将这些16:9图像再次裁剪为4:3并不是您想要的。而是通过设置self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto(在向会话添加任何输入/输出之前)从iPhone的相机获取原生4:3图像。