保存CIImage,转换为CGImage,会抛出错误

我有一个我从AVFoundation抓取的图像:

[stillImage captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error) { NSLog(@"image capture"); NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; UIImage *image = [[UIImage alloc] initWithData:imageData]; 

我然后通过首先转换为CIImage来裁剪此图像:

 beginImage = [CIImage imageWithCVPixelBuffer:CMSampleBufferGetImageBuffer(imageSampleBuffer) options:[NSDictionary dictionaryWithObjectsAndKeys:[NSNull null], kCIImageColorSpace, nil]]; //first we crop to a square crop = [CIFilter filterWithName:@"CICrop"]; [crop setValue:[CIVector vectorWithX:0 Y:0 Z:70 W:70] forKey:@"inputRectangle"]; [crop setValue:beginImage forKey:@"inputImage"]; croppedColourImage = [crop valueForKey:@"outputImage"]; 

我然后尝试将其转换回CGImage,以便我可以将其保存:

 CGImageRef cropColourImage = [context createCGImage:croppedColourImage fromRect:[croppedColourImage extent]]; UIImage *cropSaveImage = [UIImage imageWithCGImage:cropColourImage]; //saving of the images ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeImageToSavedPhotosAlbum:[cropSaveImage CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){ if (error) { NSLog(@"ERROR in image save :%@", error); } else { NSLog(@"SUCCESS in image save"); } }]; 

但是,这会引发错误:

图像保存中的错误:错误域= ALAssetsLibraryErrorDomain代码= -3304“无法为保存的照片编码图像。” UserInfo = 0x19fbd0 {NSUnderlyingError = 0x18efa0“无法对保存的照片的图像进行编码。”,NSLocalizedDescription =无法对保存的照片的图像进行编码。}

我在其他地方读过,如果图像是0x0像素,可能会发生这种情况,并且从CIImage到CGImage的转换会导致问题。 有任何想法吗?

谢谢。

我搞定了!

我所做的是用以下代码替换我的所有代码:

 NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer]; UIImage *image = [[UIImage alloc] initWithData:imageData]; NSLog(@"*image size is: %@", NSStringFromCGSize(image.size)); //test creating a new ciimage CIImage *ciImage = [[CIImage alloc] initWithCGImage:[image CGImage]]; NSLog(@"ciImage extent: %@", NSStringFromCGRect([ciImage extent])); 

这给了我一个可用的CIImage。 然后我可以使用它过滤乐趣,然后保存:

 CIImage *croppedColourImage = [crop outputImage]; //convert it to a cgimage for saving CGImageRef cropColourImage = [context createCGImage:croppedColourImage fromRect:[croppedColourImage extent]]; //saving of the images ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeImageToSavedPhotosAlbum:cropColourImage metadata:[croppedColourImage properties] completionBlock:^(NSURL *assetURL, NSError *error){ if (error) { NSLog(@"ERROR in image save: %@", error); } else { NSLog(@"SUCCESS in image save"); CGImageRelease(cropColourImage); } }];