Convert UIImage to grayscale keeping image quality

前端 未结 7 1188
难免孤独
难免孤独 2020-12-08 19:42

I have this extension (found in obj-c and I converted it to Swift3) to get the same UIImage but grayscaled:

public fun         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 20:28

    Here's a category in objective c. Note that, critically, this version takes scale into consideration.

    - (UIImage *)grayscaleImage{
        return [self imageWithCIFilter:@"CIPhotoEffectMono"];
    }
    
    - (UIImage *)imageWithCIFilter:(NSString*)filterName{
        CIImage *unfiltered = [CIImage imageWithCGImage:self.CGImage];
        CIFilter *filter = [CIFilter filterWithName:filterName];
        [filter setValue:unfiltered forKey:kCIInputImageKey];
        CIImage *filtered = [filter outputImage];
        CIContext *context = [CIContext contextWithOptions:nil];
        CGImageRef cgimage = [context createCGImage:filtered fromRect:CGRectMake(0, 0, self.size.width*self.scale, self.size.height*self.scale)];
        // Do not use initWithCIImage because that renders the filter each time the image is displayed.  This causes slow scrolling in tableviews.
        UIImage *image = [[UIImage alloc] initWithCGImage:cgimage scale:self.scale orientation:self.imageOrientation];
        CGImageRelease(cgimage);
        return image;
    }
    

提交回复
热议问题