问题
I have some issues applying filters to an image. The following code works perfect when using 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:
-(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:
CIImage *ciImage = [UIImage imageNamed:@"test.png"].CIImage;
The filtered image only turns white (or disappears). What am I doing wrong?
回答1:
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; it merely provides a reference to the CIImage that is already the basis of this UIImage. But this UIImage does not have a CIImage basis; it is a bitmap (CGImage), not a filter output (CIImage).
That is why, as you have rightly discovered, you have use a different method, CIImage's initWithCGImage:
, which does perform the conversion. The UIImage (as I just said) does have a CGImage basis, so this works.
In other words, a UIImage is (mostly) just a wrapper. It can be a wrapper for a bitmap (CGImage) or for a filter output (CIImage). And those two methods, CGImage
and CIImage
, are merely ways of obtaining what is wrapped; only one of them will work on any given UIImage, and most of the time it will be CGImage
.
回答2:
Juraj Antas' answer in this question How to Convert UIImage to CIImage and vice versa fixed my issue:
UIImage *u = [UIImage imageNamed:@"image.jpg"];
CIImage *image = [[CIImage alloc] initWithCGImage: u.CGImage];
来源:https://stackoverflow.com/questions/22795160/cgimage-from-nsurl-works-but-not-from-uiimage