我一直在努力尝试让AVFoundation相机以正确的方向(即设备方向)捕获图片,但我无法正常工作。
我看过教程,看过WWDC演示文稿,并下载了WWDC示例程序,但即使那样也没有。
我应用程式中的程式码是...
AVCaptureConnection *videoConnection = [CameraVC connectionWithMediaType:AVMediaTypeVideo fromConnections:[imageCaptureOutput connections]];
if ([videoConnection isVideoOrientationSupported])
{
[videoConnection setVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
[imageCaptureOutput captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer != NULL)
{
//NSLog(@"%d", screenOrientation);
//CMSetAttachment(imageDataSampleBuffer, kCGImagePropertyOrientation, [NSString stringWithFormat:@"%d", screenOrientation], 0);
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[self processImage:image];
}
}];
(processImage使用与WWDC代码相同的writeImage ...方法)
WWDC应用程序中的代码是...
AVCaptureConnection *videoConnection = [AVCamDemoCaptureManager connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
if ([videoConnection isVideoOrientationSupported]) {
[videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
}
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer != NULL) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(captureStillImageFailedWithError:)]) {
[delegate captureStillImageFailedWithError:error];
}
}
}];
[library release];
[image release];
} else if (error) {
id delegate = [self delegate];
if ([delegate respondsToSelector:@selector(captureStillImageFailedWithError:)]) {
[delegate captureStillImageFailedWithError:error];
}
}
}];
在他们的代码开始时,他们将AVOrientation设置为纵向,这看起来很奇怪,但是我试图让它检测设备的当前方向并使用它。
如您所见,我已经尝试使用[UIApplication sharedApplication] statusBarOrientation来进行此操作,但它仍然仅将照片保存为纵向。
任何人都可以对我需要做的事情提供任何帮助或建议吗?
谢谢!
奥立佛
最佳答案
好吧,我花了我永远的压裂,但我做到了!
我一直在寻找的代码是
[UIDevice currentDevice].orientation;
这样进去
AVCaptureConnection *videoConnection = [CameraVC connectionWithMediaType:AVMediaTypeVideo fromConnections:[imageCaptureOutput connections]];
if ([videoConnection isVideoOrientationSupported])
{
[videoConnection setVideoOrientation:[UIDevice currentDevice].orientation];
}
它完美地工作:D
哇!