我如何对UIImage进行去饱和处理?

时间:2012-06-05 18:02:46

标签: iphone objective-c ios uiimage core-graphics

在iOS 5.x中是否有一种简单的方法(或内置库)去饱和UIImage?目前我正在这样做:

CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    CGContextTranslateCTM(context, 0.0, self.bounds.size.height); // flip image right side up
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextDrawImage(context, rect, self.image.CGImage);
    CGContextSetBlendMode(context, kCGBlendModeSaturation);
    CGContextClipToMask(context, self.bounds, image.CGImage); // restricts drawing to within alpha channel
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, desaturation);
    CGContextFillRect(context, rect);

    CGContextRestoreGState(context); // restore state to reset blend mode

这似乎比我预期的要复杂一些。有比这更简单的方法吗?

我在想Core Image,但我似乎无法找到一个关于如何使用它去饱和图像的具体例子。

1 个答案:

答案 0 :(得分:21)

您可以使用我的开源GPUImage框架使用两行或三行代码执行此操作:

UIImage *inputImage = [UIImage imageNamed:@"inputimage.png"];    
GPUImageGrayscaleFilter *grayscaleFilter = [[GPUImageGrayscaleFilter alloc] init];
UIImage *grayscaleImage = [grayscaleFilter imageByFilteringImage:inputImage];

(如果不使用ARC构建,请记住释放过滤器)

这会将图像降低到亮度值,使其饱和度降低。如果需要变量饱和度/去饱和度,可以使用GPUImageSaturationFilter。正如框架名称所示,此过滤在GPU上运行,并且几乎在我从iOS 5.1开始基准测试的所有情况下都比Core Image快。