2

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

    }    
}
jscs
  • 63,694
  • 13
  • 151
  • 195
Carpetfizz
  • 8,707
  • 22
  • 85
  • 146
  • For those who are interested in this in the future here some code that invert colors of an image pixel by pixel http://stackoverflow.com/questions/24049313/how-do-i-load-and-edit-a-bitmap-file-at-the-pixel-level-in-swift-for-ios#24139701 – Khaled Annajar Oct 12 '16 at 09:46

1 Answers1

5

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.

Community
  • 1
  • 1
Guto Araujo
  • 3,824
  • 2
  • 21
  • 26
  • Not sure why the down vote. I reproduced the issue and actually tested the code above before posting the answer. – Guto Araujo Nov 11 '13 at 18:17
  • 1
    Please explain why you think that merely using a different initializer plus a method should make a difference. Your code does the exact same thing as the one from the OP, only split into two method calls. Also, simply presenting code without explanation isn't a good way of answering (even if it would be correct). – DarkDust Nov 11 '13 at 18:19