如何将UIImage转换为CIImage,反之亦然

我试图从屏幕上显示的ImageView中获取CIImage

 UIImage *image = myImageView.image; 

将图像UIImage转换为CIImage

 CIImage *cImage = [....]; 

这个怎么做?

 CIImage *ciImage = [UIImage imageNamed:@"test.png"].CIImage; UIImage *uiImage = [[UIImage alloc] initWithCIImage:ciImage]; 

为了修复myUIImage.CIImage像[UIImageView image]一样返回零的情况,你可以改为[CIImage imageWithCGImage:myUIImage.CGImage] – Dylan Hand

虽然王长兴的回答是正确的,但苹果表示,UIImage.CIImage并不总是有效。 具体来说,从PocketCoreImage:

 // Create a CIImage from the _inputImage. While UIImage has a property returning // a CIImage representation of it, there are cases where it will not work. This is the // most compatible route. _filteredImage = [[CIImage alloc] initWithCGImage:_inputImage.CGImage options:nil]; 

苹果也使用以下,这不适合我:

 [UIImage imageWithCIImage:_filteredImage] 

我的个人实施,从这个职位改编确实对我有用:

 // result is a CIImage, output of my filtering. // returnImage is (obviously) a UIImage that I'm going to return. CIContext *context = [CIContext contextWithOptions:nil]; UIImage *returnImage = [UIImage imageWithCGImage:[context createCGImage:result fromRect:result.extent]]; 

这是最合适的做法:

 UIImage* u =[UIImage imageNamed:@"image.png"]; CIImage* ciimage = [[CIImage alloc] initWithCGImage:u.CGImage]; 

现在使用ciimage …

这是我在项目中使用的完整代码示例。

 - (UIImage *)makeUIImageFromCIImage:(CIImage *)ciImage { CIContext *context = [CIContext contextWithOptions:nil]; CGImageRef cgImage = [context createCGImage:ciImage fromRect:[ciImage extent]]; UIImage* uiImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return uiImage; } 

CIImage基本上是一个图像的配方。 如果您尝试直接从CIImage转换为UIImage则会遇到问题。 例如,打电话

 NSData * UIImageJPEGRepresentation ( UIImage *image, CGFloat compressionQuality ); 

将返回nil

 func toCIImage(image: UIImage) -> CIImage { return image.CIImage ?? CIImage(CGImage: image.CGImage!) } func toUIImage(image: CIImage) -> UIImage { return UIImage(CIImage: image) } 

快速的答案的例子:

 guard let ciimage = CIImage(image: uiimage) else { return } let image = UIImage(CIImage: ciimage)