我有一个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;
}
答案 0 :(得分:22)
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;
}
(但我关闭了标签,所以我不知道从哪里得到它)