Search code examples
iosuiimageviewuiimagecore-imagecifilter

Why is my picture getting blurring after switching CIFilter?


After changing the CIFilter on an imageView image, the image appears blurry. Trying to figure out why.

Here is the code:

- (UIImage *)convertImageToGrayScale:(UIImage *)image {
    CIFilter *filter = [CIFilter filterWithName:@"CIPhotoEffectTonal"];
    CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    return [UIImage imageWithCIImage:filter.outputImage];
}

- (UIImage *)convertImageToColorScale:(UIImage *)image {
    CIFilter *filter = [CIFilter filterWithName:@"CIPhotoEffectChrome"];
    CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    return [UIImage imageWithCIImage:filter.outputImage];
}


- (IBAction)colorize:(id)sender {
    self.imageView.image = nil;
    if(self.hasColor) {
        self.hasColor = FALSE;
        self.imageView.image = [self convertImageToGrayScale:[UIImage imageWithContentsOfFile:self.filePath]];
        NSLog(@"remove Color");
    }
    else {
        self.hasColor = TRUE;
        self.imageView.image = [self convertImageToColorScale:[UIImage imageWithContentsOfFile:self.filePath]];
        NSLog(@"Add Color");
    }
}

When I add the filter the first time, it looks good. When I click the button to change the filter, it's blurry.


Solution

  • Try replacing the line return [UIImage imageWithCIImage:filter.outputImage]; with:

    CIImage *outputImage = [filter outputImage];
    CGImageRef imageRef = [[CIContext contextWithOptions:nil] createCGImage:outputImage fromRect:outputImage.extent];
    UIImage *newImg = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return newImg;