0

我有一张从 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 Code=-3304“无法为保存的照片编码图像。” UserInfo=0x19fbd0 {NSUnderlyingError=0x18efa0 "无法为保存的照片编码图像。", NSLocalizedDescription=无法为保存的照片编码图像。}

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

谢谢你。

4

1 回答 1

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);
    }
}];
于 2012-05-06T17:59:58.110 回答