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

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

UIImage *image = myImageView.image;

将图像 UIImage转换为 CIImage

CIImage *cImage = [....];

怎么做?

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

为了解决这种情况下 myUIImage.CIImage返回 nil[UIImageView image],你可以做 [CIImage imageWithCGImage:myUIImage.CGImage]-迪伦手

快速版:

let ciImage = UIImage(named: "test.png")!.ciImage
let uiImage = UIImage(ciImage: ciImage)

修正了 myUIImage.ciImage返回 nil的情况,就像你可以返回 CIImage(cgImage: myUIImage!.cgImage!)一样。

尽管王的回答实际上是正确的,但苹果表示,UIImage.CIImage 并不总是有效:

// 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..。

迅捷版本:

let i1 = UIImage(named: "testImage")
if let cgi1 = i1?.cgImage {
let ci = CIImage(cgImage: cgi1)
//use ci
}

(修正了 if let 语句中的输入错误)

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

- (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)

斯威夫特3/4

UIImage > CIImage

let ciimage = CIImage(image: image)

Https://developer.apple.com/documentation/uikit/uiimage/1624090-init

CIImage > UIImage

let image = UIImage(ciImage: ciimage)

Https://developer.apple.com/documentation/coreimage/ciimage/1624119-init

在将 UIImage 转换为 CIImage 时,我遇到了两个不同的情况,有时是0,有时不是。下面的代码解决了这个问题:

CIImage *ciImage;
ciImage=[[CIImage alloc] initWithImage:imageToConvert];
if (ciImage==nil)
ciImage=imageToConvert.CIImage;