Захваченное фото растягивается с помощью AVCaptureSession sessionPreset = AVCaptureSessionPresetPhoto

ВАЖНО: если я использую: session.sessionPreset = AVCaptureSessionPresetHigh; мое изображение для предварительного просмотра не растягивается!! Если сохраняю фото на устройство UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); изображение нормальное, только на превью растянуто.

Я использую AVFoundation для захвата фотографий.

session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetHigh;

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

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

captureVideoPreviewLayer.frame = vImagePreview.bounds;
[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];

Я установил sessionPreset на AVCaptureSessionPresetPhoto:

session.sessionPreset = AVCaptureSessionPresetPhoto;

Мой метод захвата:

-(void)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];
         NSLog(@"%@",NSStringFromCGSize(image.size));
         [self animateUpTheImageWithImage:image];


     }];

}

Где я добавляю предварительный просмотр захваченной фотографии:

- (void) animateUpTheImageWithImage:(UIImage*)theImage{

    UIView* preview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height/*426*/)];
    CALayer *previewLayer = preview.layer;
    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    captureVideoPreviewLayer.frame = previewLayer.frame;
    [previewLayer addSublayer:captureVideoPreviewLayer];
    captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspect;

    [self addSubview:preview];

}

И в результате мое захваченное изображение растянуто!

Захват предварительного просмотра камеры

Предварительный просмотр захваченного изображения


person incmiko    schedule 04.10.2013    source источник
comment
К AVCapture абсолютно никакого отношения не имеет, если сохраненное фото не растянуто. Вы думали об этом?   -  person Sergey Grischyov    schedule 04.10.2013
comment
Эй, @incmiko, ты когда-нибудь это понимал? У меня сейчас такая же проблема. Целый день работал над этим и до сих пор не нашел способа это исправить.   -  person user3117509    schedule 20.02.2014
comment
Я ответил на свой вопрос, смотрите ниже. Я надеюсь, что это решит и вашу проблему.   -  person incmiko    schedule 21.02.2014


Ответы (3)


Итак, я решил свою проблему. Вот код, который я использую сейчас, и он отлично работает:

    session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetHigh;

    captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    captureVideoPreviewLayer.frame = vImagePreview.bounds;
    [vImagePreview.layer addSublayer:captureVideoPreviewLayer];

    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

...

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

capturedImageView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.screenWidth,self.screenHeight)];
[self addSubview:capturedImageView];

и важен вывод imagaView:

vImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.screenWidth,self.screenHeight)];
    [capturedImageView addSubview:vImage];
    vImage.autoresizingMask = (UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth);
    vImage.contentMode = UIViewContentModeScaleAspectFill;
    vImage.image = theImage;

Некоторая дополнительная информация:

слой камеры должен быть полноэкранным (вы можете изменить его координату y, но ширина и высота должны быть в полном размере), и outputImageView тоже должен быть.

Я надеюсь, что это будет полезная информация для кого-то тоже.

person incmiko    schedule 21.02.2014
comment
что вы имеете в виду, используя vImage Apple, AVCam не имеет этого в источниках? - person Matrosov Alexander; 09.09.2014

Попробуйте использовать [captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

person Sergey Grischyov    schedule 04.10.2013
comment
это ничего не делает, мой предварительный просмотр такой же. session.sessionPreset = AVCaptureSessionPresetHigh; правильно работать с этим. session.sessionPreset = AVCaptureSessionPresetPhoto; предварительный просмотр плохой - person incmiko; 04.10.2013
comment
@incmiko Вы пробовали все остальные типы переменных AVLayerVideoGravity? - person Sergey Grischyov; 04.10.2013
comment
да, этот метод работает только с предварительным просмотром камеры, результат будет сохранен в растянутом виде - person Matrosov Alexander; 09.09.2014

Изменить SessionPreset захвата на AVCaptureSessionPresetiFrame960x540; и это хорошо работает для меня.

person Tarun    schedule 18.06.2015