Search code examples
objective-cuiimagecifilterciimage

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:

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?


Solution

  • 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];