通过转换为CGImage来保存CIImage会引发错误

时间:2012-05-04 10:43:29

标签: ios uiimage 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的转换会导致问题。有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

我开始工作了!

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

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);
    }
}];