是否可以以编程方式反转图像的颜色?

时间:2011-07-12 23:40:20

标签: iphone ios ipad uiimage

我想在iOS中拍摄图像并反转颜色。

7 个答案:

答案 0 :(得分:41)

要扩展quixoto的答案,因为我有自己的项目的相关源代码,如果你需要放弃CPU上的像素操作,那么我已经添加了以下内容,应该这样做特技:

@implementation UIImage (NegativeImage)

- (UIImage *)negativeImage
{
    // get width and height as integers, since we'll be using them as
    // array subscripts, etc, and this'll save a whole lot of casting
    CGSize size = self.size;
    int width = size.width;
    int height = size.height;

    // Create a suitable RGB+alpha bitmap context in BGRA colour space
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *memoryPool = (unsigned char *)calloc(width*height*4, 1);
    CGContextRef context = CGBitmapContextCreate(memoryPool, width, height, 8, width * 4, colourSpace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colourSpace);

    // draw the current image to the newly created context
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self CGImage]);

    // run through every pixel, a scan line at a time...
    for(int y = 0; y < height; y++)
    {
        // get a pointer to the start of this scan line
        unsigned char *linePointer = &memoryPool[y * width * 4];

        // step through the pixels one by one...
        for(int x = 0; x < width; x++)
        {
            // get RGB values. We're dealing with premultiplied alpha
            // here, so we need to divide by the alpha channel (if it
            // isn't zero, of course) to get uninflected RGB. We
            // multiply by 255 to keep precision while still using
            // integers
            int r, g, b; 
            if(linePointer[3])
            {
                r = linePointer[0] * 255 / linePointer[3];
                g = linePointer[1] * 255 / linePointer[3];
                b = linePointer[2] * 255 / linePointer[3];
            }
            else
                r = g = b = 0;

            // perform the colour inversion
            r = 255 - r;
            g = 255 - g;
            b = 255 - b;

            // multiply by alpha again, divide by 255 to undo the
            // scaling before, store the new values and advance
            // the pointer we're reading pixel data from
            linePointer[0] = r * linePointer[3] / 255;
            linePointer[1] = g * linePointer[3] / 255;
            linePointer[2] = b * linePointer[3] / 255;
            linePointer += 4;
        }
    }

    // get a CG image from the context, wrap that into a
    // UIImage
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];

    // clean up
    CGImageRelease(cgImage);
    CGContextRelease(context);
    free(memoryPool);

    // and return
    return returnImage;
}

@end

这样就为UIImage添加了一个类别方法:

  1. 创建一个清晰的CoreGraphics位图上下文,它可以访问
  2. 的内存
  3. 将UIImage绘制到它
  4. 贯穿每个像素,从预乘的alpha转换为未反射的RGB,分别反转每个通道,再次乘以alpha并存储回来
  5. 从上下文中获取图像并将其包装到UIImage
  6. 自行清理,并返回UIImage

答案 1 :(得分:21)

使用CoreImage:

#import <CoreImage/CoreImage.h>

@implementation UIImage (ColorInverse)

+ (UIImage *)inverseColor:(UIImage *)image {
    CIImage *coreImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIColorInvert"];
    [filter setValue:coreImage forKey:kCIInputImageKey];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    return [UIImage imageWithCIImage:result];
}

@end

答案 2 :(得分:4)

当然,这是可能的 - 一种方法是使用“差异”混合模式(kCGBlendModeDifference)。有关设置图像处理的代码概要,请参阅this question(以及其他)。使用图像作为底部(基础)图像,然后在其上绘制纯白色位图。

您还可以手动执行每像素操作,方法是获取CGImageRef并将其绘制到位图上下文中,然后循环遍历位图上下文中的像素。

答案 3 :(得分:3)

Tommy回答是答案,但我想指出,对于更大的图像来说,这可能是一项非常耗时且耗时的任务。有两个框架可以帮助您操作图像:

  1. CoreImage
  2. 加速器

    值得一提的是来自Brad Larson的令人惊叹的GPUImage框架,GPUImage使用OpenGlES 2.0环境中的自定义片段着色器在GPU上运行例程,并显着提高速度。使用CoreImge,如果负过滤器可用,您可以选择CPU或GPU,使用Accelerator所有例程在CPU上运行,但使用矢量数学图像处理。

答案 4 :(得分:3)

创建了一个快速扩展来做到这一点。另外,因为基于CIImage的UIImages分解(大多数库假设CGImage已设置),我添加了一个选项来返回基于修改后的CIImage的UIImage:

extension UIImage {
    func inverseImage(cgResult: Bool) -> UIImage? {
        let coreImage = UIKit.CIImage(image: self)
        guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
        filter.setValue(coreImage, forKey: kCIInputImageKey)
        guard let result = filter.valueForKey(kCIOutputImageKey) as? UIKit.CIImage else { return nil }
        if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
            return UIImage(CGImage: CIContext(options: nil).createCGImage(result, fromRect: result.extent))
        }
        return UIImage(CIImage: result)
    }
}

答案 5 :(得分:0)

Swift 3更新: (来自@BadPirate答案)

extension UIImage {
func inverseImage(cgResult: Bool) -> UIImage? {
    let coreImage = UIKit.CIImage(image: self)
    guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
    filter.setValue(coreImage, forKey: kCIInputImageKey)
    guard let result = filter.value(forKey: kCIOutputImageKey) as? UIKit.CIImage else { return nil }
    if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
        return UIImage(cgImage: CIContext(options: nil).createCGImage(result, from: result.extent)!)
    }
    return UIImage(ciImage: result)
  }
}

答案 6 :(得分:0)

已更新为@MLBDG答案的Swift 5版本

extension UIImage {
func inverseImage(cgResult: Bool) -> UIImage? {
    let coreImage = self.ciImage
    guard let filter = CIFilter(name: "CIColorInvert") else { return nil }
    filter.setValue(coreImage, forKey: kCIInputImageKey)
    guard let result = filter.value(forKey: kCIOutputImageKey) as? UIKit.CIImage else { return nil }
    if cgResult { // I've found that UIImage's that are based on CIImages don't work with a lot of calls properly
        return UIImage(cgImage: CIContext(options: nil).createCGImage(result, from: result.extent)!)
    }
    return UIImage(ciImage: result)
}

}