如何使用AVCaptureDevice保存图像

时间:2013-09-12 09:41:37

标签: ios objective-c avcapturesession avcapture avcapturedevice

我在我的项目中使用Apple的GLCameraRipple示例代码,我想知道是否有办法拍摄照片/视频?项目可以在https://developer.apple.com/library/ios/samplecode/GLCameraRipple/Introduction/Intro.html

找到

1 个答案:

答案 0 :(得分:1)

首先,确保您已包含AssetLibrary框架,因为我们需要它来访问照片库。假设您已正确设置捕获AVCaptureSession,AVCaptureDevice和AVCaptureStillImageOutput(stillImage),现在您可以创建一个按钮或只需调用以下函数来保存图像。

-(void)captureMultipleTimes
{
AVCaptureConnection *connection = [stillImage connectionWithMediaType:AVMediaTypeVideo];

typedef void(^MyBufBlock)(CMSampleBufferRef, NSError*);

MyBufBlock h = ^(CMSampleBufferRef buf, NSError *err){
    NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:buf];
    [self setToSaveImage:[UIImage imageWithData:data]];

    dispatch_async(dispatch_get_main_queue(), ^{
        if(saveLabel == NULL){
            [self setSaveLabel:[[UILabel alloc] initWithFrame:CGRectMake(0,self.view.bounds.size.height/2, self.view.bounds.size.width, 50)]];
            [saveLabel setText:@"Saving.."];
            [saveLabel setTextColor:[captureBt titleColorForState:UIControlStateNormal]];
            [self.view addSubview:saveLabel];
        } else
            saveLabel.hidden = NO;

        UIImageWriteToSavedPhotosAlbum(toSaveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    });
};
[stillImage captureStillImageAsynchronouslyFromConnection:connection completionHandler:h];
}

您还需要实现 image:didFinishSavingWithError:contextInfo:方法作为保存图像的完成功能。一个例子如下:

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if(error != NULL){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Image could not be saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
else{
    [saveLabel setHidden:YES];
}
}

触发captureMultipleTimes功能后,上面的功能会在屏幕上显示“Saving ..”标签。它只是意味着它当前将视频输入保存为图像并将其存储到照片库中。保存完成后,保存标签将在屏幕上隐藏。希望这有帮助!