【问题标题】:How to take square picture in iphone with avFoundation like in Instagram app?如何在 iphone 中使用 avFoundation 像 Instagram 应用一样拍摄方形照片?
【发布时间】:2012-06-07 09:51:27
【问题描述】:

我正在与 AVFoundation 合影,如下所示: http://red-glasses.com/index.php/tutorials/ios4-take-photos-with-live-video-preview-using-avfoundation/

一个sn-p:

[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


    【解决方案1】:

    您可能应该通过创建新上下文来调整 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
    

    希望这会有所帮助!

    【讨论】:

    • 这是唯一的方法吗?我想如果调整大小,图像会看起来更糟。是否可以拍摄自定义尺寸而不调整其大小?
    • 没有一个相机可以拍摄不同尺寸的照片。如果您使用较小的图像,它将始终使用完整分辨率并将其缩小。除了从完整图像中裁剪出一个矩形之外,Instagram 也别无他法。在此示例中,大小为400px,但您可以看到原始图像的宽度并制作一个高度相同的矩形。它将产生一个方形图像,并且您会在上方和下方丢失一些像素。
    • 缩小图像,假设适当的插值,使它看起来更好而不是更糟,所以你的担心是没有根据的。
    • 照片尺寸有不同的预设,小尺寸拍照效率更高,速度更快,AVCaptureSessionPresetMedium应该足够了
    【解决方案2】:

    我找到了一个使用 AVCaptureSession 和this is a great tutorial by "JJob" 拍照的代码。是最好的关于 AVCaptureSession 的教程;请阅读本网站的所有 cmets 和以前的教程,这将对您有很大帮助。您可以从here 下载工作示例代码。

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 2016-08-26
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多