如何将使用AVFoundation拍摄的照片保存到相册中?

12

AVFoundation非常适合那些想要深入了解的人,但仍有很多基础知识不容易弄清楚,比如如何将从设备拍摄的照片保存到相册中。

有任何想法吗?


这个话题似乎与Cocoa无关。 - El Tomato
4个回答

61

这是一个逐步教程,教你如何使用AVFoundation捕获图像并将其保存到照片库中。

在 NIB 中添加一个UIView对象(或者作为子视图),并在控制器中创建一个@property属性:

@property(nonatomic, retain) IBOutlet UIView *vImagePreview;

在IB中将UIView连接到上面的outlet,或者如果您使用代码而不是NIB,则直接分配它。

然后编辑您的UIViewController,并提供以下viewDidAppear方法:

-(void)viewDidAppear:(BOOL)animated
{
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    CALayer *viewLayer = self.vImagePreview.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
    [self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [stillImageOutput setOutputSettings:outputSettings];
    [session addOutput:stillImageOutput];

    [session startRunning];
}
创建一个新的@property来保存引用输出对象的内容:
@property(nonatomic, retain) AVCaptureStillImageOutput *stillImageOutput;

接下来创建一个UIImageView,用于显示拍摄的照片。将其添加到NIB中或以编程方式添加。

将其连接到另一个@property,或手动分配,例如:

@property(nonatomic, retain) IBOutlet UIImageView *vImage;

最后,创建一个UIButton,这样你就可以拍照了。

同样,将其添加到你的NIB文件(或以编程方式添加到屏幕上),并连接到以下方法:

-(IBAction)captureNow {
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in 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: %@", stillImageOutput);
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
    {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments)
         {
            // Do something with the attachments.
            NSLog(@"attachements: %@", exifAttachments);
         } else {
            NSLog(@"no attachments");
             }

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

        self.vImage.image = image;

        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
     }];
}

你可能还需要导入 #import <ImageIO/CGImageProperties.h>

来源。 也可以查看这里


2
我强烈推荐其他人访问此帖子中链接的网站。它们可以更深入地了解正在发生的事情。很棒的帖子,iDev! - user353955
工作得很好。也许还应该调用 [super viewDidAppear:animated]。 - Runo Sahara
非常感谢。我有它的Swift版本代码。需要的人,请告诉我。 - nitin.agam

1
根据您的问题,看起来您已经将图片从相机中转换为NSData或UIImage。如果是这样,您可以以不同的方式将此图片添加到相册中。AVFoundation本身没有保存图像的类。
例如,您可以使用ALAssetsLibrary框架将图像保存到照片库中。或者您可以只使用UIKit框架及其UIImageWriteToSavedPhotosAlbum方法。两种方法都很好用。
如果您还没有捕获静态图像,您可以查看AVFoundation框架的captureStillImageAsynchronouslyFromConnection方法。
无论如何,这些都是想法。您可以在互联网上轻松找到示例。祝您好运 :)

0

这个方法对我有效

-(void) saveImageDataToLibrary:(UIImage *) image
{
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
[appDelegate.library writeImageDataToSavedPhotosAlbum:imageData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error)
{
    if (error) {
        NSLog(@"%@",error.description);
    }
    else {
        NSLog(@"Photo saved successful");
    }
}];
}

其中 appDelegate.library 是 ALAssetLibrary 实例。


谢谢,但是您是如何使用AVFoundation从前置摄像头设备中提取UIImage的呢? - RollRoll

0

按照这种方式设置相机有很多细节你可能没有处理好,或者没有展示。

最好的方法是查看AVCamCaptureManager.m文件,它在AVCam示例项目中;特别是setupSessioncaptureStillImage(它将照片保存到媒体库)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接