[英]CGImage from NSURL works but not from UIImage
I have some issues applying filters to an image. 我在将滤镜应用于图像时遇到一些问题。 The following code works perfect when using CIImage:imageWithContentsOfURL: 使用CIImage:imageWithContentsOfURL时,以下代码可以完美地工作:
NSInteger filterIndex = [(UITapGestureRecognizer *)sender view].tag;
Filter *filter = [filters objectAtIndex:filterIndex];
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *image = [CIImage imageWithContentsOfURL:[NSURL URLWithString:@"http://url.to/photo.jpg"]];
[filter.filter setValue:image forKey:kCIInputImageKey];
CIImage *result = [filter.filter valueForKey:kCIOutputImageKey];
CGRect extent = [result extent];
CGImageRef cgImage = [context createCGImage:result fromRect:extent];
[self.imageView setImage:[UIImage imageWithCGImage:cgImage]];
Filter is just a model holding filter name and CIFilter: 过滤器只是一个包含过滤器名称和CIFilter的模型:
-(id)initWithNameAndFilter:(NSString *)theName filter:(CIFilter *)theFilter;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) CIFilter *filter;
But when I try to load a local UIImage with the following code: 但是,当我尝试使用以下代码加载本地UIImage时:
CIImage *ciImage = [UIImage imageNamed:@"test.png"].CIImage;
The filtered image only turns white (or disappears). 过滤后的图像只会变成白色(或消失)。 What am I doing wrong? 我究竟做错了什么?
The problem is that 问题是
[UIImage imageNamed:@"test.png"].CIImage
doesn't do what you think it does. 不按照您的想法去做。 It doesn't convert a UIImage into a CIImage, or derive a CIImage from a UIImage; 它不会将UIImage转换为CIImage,也不会从UIImage派生CIImage。 it merely provides a reference to the CIImage that is already the basis of this UIImage. 它仅提供对CIImage的引用,而该CIImage 已经是此UIImage的基础。 But this UIImage does not have a CIImage basis; 但是,这UIImage的没有一个CIImage基础; it is a bitmap (CGImage), not a filter output (CIImage). 它是位图(CGImage),而不是过滤器输出(CIImage)。
That is why, as you have rightly discovered, you have use a different method, CIImage's initWithCGImage:
, which does perform the conversion. 这就是为什么,因为你已经正确地发现,你必须使用不同的方法,CIImage的initWithCGImage:
它不执行转换。 The UIImage (as I just said) does have a CGImage basis, so this works. UIImage(正如我刚才说的) 确实具有CGImage基础,因此可以正常工作。
In other words, a UIImage is (mostly) just a wrapper . 换句话说,UIImage(通常)只是一个包装器 。 It can be a wrapper for a bitmap (CGImage) or for a filter output (CIImage). 它可以是位图(CGImage)或过滤器输出(CIImage)的包装。 And those two methods, CGImage
and CIImage
, are merely ways of obtaining what is wrapped; 而这两种方法CGImage
和CIImage
仅仅是获取包装内容的方法。 only one of them will work on any given UIImage, and most of the time it will be CGImage
. 其中只有一个可以在任何给定的UIImage上工作,并且大多数情况下是CGImage
。
Juraj Antas' answer in this question How to Convert UIImage to CIImage and vice versa fixed my issue: Juraj Antas在此问题中的回答如何将UIImage转换为CIImage,反之亦然,解决了我的问题:
UIImage *u = [UIImage imageNamed:@"image.jpg"];
CIImage *image = [[CIImage alloc] initWithCGImage: u.CGImage];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.