所以我一整天都没有运气,不用说非常令人沮丧,我查找了许多示例和可下载的类别,它们都吹捧能够完美地裁剪图像。他们这样做了,但是当我尝试从通过 AVCaptureSession 生成的图像中执行此操作时,它就无法正常工作。我咨询了这两个来源
http://codefuel.wordpress.com/2011/04/22/image-cropping-from-a-uiscrollview/
http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
并且第一个链接中的项目似乎可以直接像宣传的那样工作,但是一旦我破解它以在 av 捕获图像上做同样的魔法......不......
有人对此有见识吗?这里也是我的代码供参考。
- (IBAction)TakePhotoPressed:(id)sender
{
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(@"%f",image.size.width);
NSLog(@"%f",image.size.height);
float scale = 1.0f/_scrollView.zoomScale;
CGRect visibleRect;
visibleRect.origin.x = _scrollView.contentOffset.x * scale;
visibleRect.origin.y = _scrollView.contentOffset.x * scale;
visibleRect.size.width = _scrollView.bounds.size.width * scale;
visibleRect.size.height = _scrollView.bounds.size.height * scale;
UIImage* cropped = [self cropImage:image withRect:visibleRect];
[croppedImage setImage:cropped];
[image release];
}
];
[croppedImage setHidden:NO];
}
上面使用的cropImage 函数。
-(UIImage*)cropImage :(UIImage*)originalImage withRect :(CGRect) rect
{
CGRect transformedRect=rect;
if(originalImage.imageOrientation==UIImageOrientationRight)
{
transformedRect.origin.x = rect.origin.y;
transformedRect.origin.y = originalImage.size.width-(rect.origin.x+rect.size.width);
transformedRect.size.width = rect.size.height;
transformedRect.size.height = rect.size.width;
}
CGImageRef cr = CGImageCreateWithImageInRect(originalImage.CGImage, transformedRect);
UIImage* cropped = [UIImage imageWithCGImage:cr scale:originalImage.scale orientation:originalImage.imageOrientation];
[croppedImage setFrame:CGRectMake(croppedImage.frame.origin.x,
croppedImage.frame.origin.y,
cropped.size.width,
cropped.size.height)];
CGImageRelease(cr);
return cropped;
}
我也很想冗长,并为任何可能帮助我解决困境的人提供尽可能多的信息,以发布我的 scrollView 和 avcapture 会话的初始化。然而,这可能有点太多了,所以如果你想看到它就问吧。
现在至于代码实际执行的结果?...
我拍照前的样子
之后...
编辑:
好吧,我现在有一些意见,没有评论,所以要么没有人想通,要么他们认为我会再次想通它是如此简单......无论如何,我没有取得任何进展。因此,对于任何对此感兴趣的人来说,这里有一个小示例应用程序,所有代码都已设置好,您可以看到我在做什么
https://docs.google.com/open?id=0Bxr4V3a9QFM_NnoxMkhzZTVNVEE