简体   繁体   English

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

[英]How do I desaturate a UIImage?

Is there an easy way (or a built-in library) in iOS 5.x to desaturate a UIImage? 在iOS 5.x中是否有一种简单的方法(或内置库)去饱和UIImage? Here's currently how I am doing it: 这是我目前的做法:

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

This seems to be a bit more complicated than I expected. 这似乎比我预期的要复杂一些。 Is there a simpler way than this? 有比这更简单的方法吗?

I was thinking of Core Image, but I can't seem to find a concrete example on how to do desaturate an image using that. 我在想Core Image,但我似乎无法找到一个关于如何使用它去饱和图像的具体例子。

You can do this with my open source GPUImage framework using two or three lines of code: 您可以使用我的开源GPUImage框架使用两行或三行代码执行此操作:

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

(remembering to release the filter if not building using ARC) (如果不使用ARC构建,请记住释放过滤器)

This reduces the image to its luminance values, desaturating it. 这将图像降低到其亮度值,使其饱和。 If you want variable saturation / desaturation, you can use a GPUImageSaturationFilter. 如果需要变量饱和度/去饱和度,可以使用GPUImageSaturationFilter。 As the framework name indicates, this filtering runs on the GPU, and is faster than Core Image in almost every situation I've benchmarked on iOS as of 5.1. 正如框架名称所示,此过滤在GPU上运行,并且几乎在我从iOS 5.1开始基准测试的所有情况下都比Core Image快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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