从CIImage获取CGImage

时间:2013-01-18 15:44:18

标签: ios core-graphics core-image cgimage ciimage

我有一个UIImage,它是从CIImage加载的:

tempImage = [UIImage imageWithCIImage:ciImage];

问题是我需要将tempImage裁剪为特定CGRect,而我知道如何执行此操作的唯一方法是使用CGImage。 问题是在iOS 6.0文档中我发现了这个:

CGImage
If the UIImage object was initialized using a CIImage object, the value of the property is NULL.

一个。如何转换CIImage至CGImage? 我正在使用此代码,但我有内存泄漏(并且无法理解在哪里):

+(UIImage*)UIImageFromCIImage:(CIImage*)ciImage {  
    CGSize size = ciImage.extent.size;  
    UIGraphicsBeginImageContext(size);  
    CGRect rect;  
    rect.origin = CGPointZero;  
    rect.size   = size;  
    UIImage *remImage = [UIImage imageWithCIImage:ciImage];  
    [remImage drawInRect:rect];  
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext();  
    remImage = nil;  
    ciImage = nil;  
    //
    return result;  
}

3 个答案:

答案 0 :(得分:22)

请参阅createCGImage:fromRect:

CIContext文档
CGImageRef img = [myContext createCGImage:ciImage fromRect:[ciImage extent]];

从回答类似问题:https://stackoverflow.com/a/10472842/474896

此外,由于您开始使用CIImage,因此您可以使用CIFilter来实际裁剪图片。

答案 1 :(得分:13)

Swift 3 Swift 4 Swift 5

这是一个很好的小函数,可以在Swift中将CIImage转换为CGImage

func convertCIImageToCGImage(inputImage: CIImage) -> CGImage? {
    let context = CIContext(options: nil)
    if let cgImage = context.createCGImage(inputImage, from: inputImage.extent) {
        return cgImage
    }
    return nil
}

答案 2 :(得分:-3)

经过一些谷歌搜索后,我发现这个方法将CMSampleBufferRef转换为CGImage:

+ (CGImageRef)imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer // Create a CGImageRef from sample buffer data
{
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);        // Lock the image buffer

    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);   // Get information of the image
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    CGImageRef newImage = CGBitmapContextCreateImage(newContext);
    CGContextRelease(newContext);

    CGColorSpaceRelease(colorSpace);
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    /* CVBufferRelease(imageBuffer); */  // do not call this!

    return newImage;
}

(但我关闭了标签,所以我不知道从哪里得到它)