3

我设置了AVCaptureSession预设的 PhotoPreset

self.session.sessionPreset = AVCaptureSessionPresetPhoto;

然后在我的视图中添加一个新图层

 AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [self.view layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:[rootLayer bounds]];
[rootLayer addSublayer:previewLayer];

到目前为止一切顺利,但是当我想捕捉图像时,我使用下面的代码

 AVCaptureConnection *videoConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];

[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
 {

     [self.session stopRunning];

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

     self.imageView.image = image; //IMAGEVIEW IS WITH THE BOUNDS OF SELF.VIEW
     image = nil;


 }];

捕获图像很好,但是与AVCaptureVideoPreviewLayer在屏幕上显示的图像相比,捕获的图像有所不同。我真正想做的是显示捕获的内容就像出现在AVCapturePreviewLayer图层上一样。我怎样才能做到这一点?我应该如何调整和裁剪捕获的图像的边界self.view

4

1 回答 1

-1

我不确定这是否会对您有所帮助,但是当您谈论裁剪图像时,我使用以下代码在 ImagePickerView 中裁剪图像我不确定这是否会对您有所帮助

- (void)imagePickerController:(UIImagePickerController *)picker 
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.lastChosenMediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([lastChosenMediaType isEqual:(NSString *)kUTTypeImage]) {
        UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
        UIImage *shrunkenImage = shrinkImage(chosenImage, imageFrame.size);
        self.imagee = shrunkenImage;
        selectImage.image = imagee;

    }     [picker dismissModalViewControllerAnimated:YES];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {    
    [picker dismissModalViewControllerAnimated:YES];
}

// function for cropping images you can do some changes in parameter as per your requirements  
static UIImage *shrinkImage(UIImage *original, CGSize size) {
    CGFloat scale = [UIScreen mainScreen].scale;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(NULL, size.width * scale,
                                                 size.height * scale, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context,
                       CGRectMake(0, 0, size.width * scale, size.height * scale),
                       original.CGImage);
    CGImageRef shrunken = CGBitmapContextCreateImage(context);
    UIImage *final = [UIImage imageWithCGImage:shrunken];

    CGContextRelease(context);
    CGImageRelease(shrunken);   

    return final;
}
于 2013-04-23T12:27:03.637 回答