Ответ 1
Ниже приведено пошаговое руководство по захвату изображения с помощью AVFoundation
и сохранению его в фотоальбоме.
Добавьте объект UIView
в NIB (или как подвью) и создайте в контроллере @property
:
@property(nonatomic, retain) IBOutlet UIView *vImagePreview;
Подключите UIView
к выходу выше в IB или назначьте его напрямую, если вы используете код вместо 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>
.