简体   繁体   中英

Passing a UIImage through a CIFilter produces a blank image

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

    }    
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM