Question

My app adds a filter to a selected image. The app works like this:

  1. An image is selected from an image picker
  2. The image is loaded as an ivar of my view controller
  3. A button is pressed to add the filter to the image

When I press the button to add a filter, the main image view goes completely white. However, when I initially load the image from the picker, it shows up fine. Here's the code that adds the filter.

- (IBAction)addFilter:(id)sender {
    if(_imageToFilter)
    {
        CIImage *newImage = _imageToFilter.CIImage;
        CIFilter *myFilter = [CIFilter filterWithName:@"CIColorInvert" keysAndValues:@"inputImage",newImage, nil];
        CIImage *filteredImage = [myFilter outputImage];
        UIImage *outputImage = [UIImage imageWithCIImage:filteredImage];
        [mainImage setImage:outputImage];

    }    
}
Was it helpful?

Solution

The problem is likely with the CIImage *inputImage being assigned nil. Try using CIImage's initWithImage: instead of _imageToFilter.CIImage (more on the edits below):

-(IBAction)addFilter:(id)sender {
    if(_imageToFilter) {
      CIImage *inputImage = [[CIImage alloc] initWithImage:_imageToFilter];
      CIFilter *myFilter = [CIFilter filterWithName:@"CIColorInvert" keysAndValues:@"inputImage",newImage, nil];
      CIImage *filteredImage = [myFilter outputImage];
      UIImage *outputImage = [UIImage imageWithCIImage:filteredImage];
      [mainImage setImage:outputImage];
    }
}

Edit: per feedback from comments, the problem seems to be that _imageToFilter.CIImage returns nil. From the docs: "If the UIImage object was initialized using a CGImageRef, the value of the property is nil."

Using the CIImage initialization method initWithImage: initializes a CIImage object with a UIImage so it solves the problem. The rest of the code works fine, so I've returned it to the original filterWithName:keysAndValues: to stay focused on the problematic part. More re: the issue here: Could anyone tell me why UIImage.ciimage is null

Thanks for the feedback and hope the answer helps the OP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top