如何在Instagram应用程序中使用avFoundation拍摄iphone中的方形图片?

Dix*_*ine 9 iphone camera avfoundation uiimage instagram

我正在像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];
Run Code Online (Sandbox Code Playgroud)

我发现的图片大小设置在这里:

   AVCaptureSession *session = [[AVCaptureSession alloc] init];  
   session.sessionPreset =AVCaptureSessionPresetMedium; //medium on my iphone4 is 640*480
Run Code Online (Sandbox Code Playgroud)

但是这里只有少数几种设置,并且无法设置为自定义大小.

如果可能的话,我想拍照片的宽高比为1:1,例如400x400像素(方形图片).看来instagram正在这样做(或者是裁剪图像?).

如何指定拍摄照片的大小为正方形?我知道如何改变手机的尺寸,但如果拍摄的照片不是正方形,结果就不好了.

任何的想法?

skr*_*ram 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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 !