如何像avFoundation一样在iPhone中拍摄方形图片?

问题描述 投票:9回答:2

我正在像下面这样通过AVFoundation拍照:http://red-glasses.com/index.php/tutorials/ios4-take-photos-with-live-video-preview-using-avfoundation/

一个片段:

[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];

据我发现的图片尺寸在这里设置:

   AVCaptureSession *session = [[AVCaptureSession alloc] init];  
   session.sessionPreset =AVCaptureSessionPresetMedium; //medium on my iphone4 is 640*480

但是这里只有少数设置,不能设置为自定义大小。

如果可能的话,我希望拍摄的图片的宽高比为1:1,例如400x400像素(方形图片)。似乎instagram正在这样做(或者它们正在裁剪图像?)。

如何将拍摄的图片的大小指定为正方形?我知道如何在手机上更改尺寸,但是如果所拍摄的照片不是方形的,则效果不佳。

任何想法?

iphone camera uiimage avfoundation instagram
2个回答
11
投票

您可能应该通过创建新的上下文来调整UIImage的大小。以下示例

.....
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImage *tempImage = nil;
CGSize targetSize = CGSizeMake(400,400);
UIGraphicsBeginImageContext(targetSize);

CGRect thumbnailRect = CGRectMake(0, 0, 0, 0);
thumbnailRect.origin = CGPointMake(0.0,0.0);
thumbnailRect.size.width  = targetSize.width;
thumbnailRect.size.height = targetSize.height;

[image drawInRect:thumbnailRect];

tempImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

// tmpImage is resized to 400x400

希望这会有所帮助!


0
投票

我发现了一个使用AVCaptureSession和this is a great tutorial by "JJob"拍照的代码。这是有关AVCaptureSession的最佳教程。请阅读本网站的所有评论和以前的教程,这对您有很大帮助。您可以从here下载有效的示例代码。

© www.soinside.com 2019 - 2024. All rights reserved.