如何在Objective-C中将UIImage转换为黑白UIImage?

时间:2015-10-24 04:04:16

标签: ios objective-c uiimage

我不想要灰度,而是让较暗的颜色变黑,打火机变成白色。我怎样才能做到这一点?我在Getting a Black and White UIImage (Not Grayscale)发现了一些看起来很有希望的东西,但代码中的下面一行给出了一个我无法解决的错误。

CGContextRef contex = CreateARGBBitmapContext(image.size); 

3 个答案:

答案 0 :(得分:1)

您应该使用GPUImage

GPUImageAdaptiveThresholdFilterGPUImageLuminanceThresholdFilter可能是您正在寻找的。

示例代码:

UIImage *image = [UIImage imageNamed:@"yourimage.png"];
GPUImageLuminanceThresholdFilter *filter = [[GPUImageLuminanceThresholdFilter alloc] init];
UIImage *quickFilteredImage = [filter imageByFilteringImage:image];

希望这有帮助!

答案 1 :(得分:0)

您可以使用以下代码转换黑白图像。

-(UIImage *)convertOriginalImageToBWImage:(UIImage *)originalImage
{
UIImage *newImage;

CGColorSpaceRef colorSapce = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(nil, originalImage.size.width * originalImage.scale, originalImage.size.height * originalImage.scale, 8, originalImage.size.width * originalImage.scale, colorSapce, kCGImageAlphaNone);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextSetShouldAntialias(context, NO);
CGContextDrawImage(context, CGRectMake(0, 0, originalImage.size.width, originalImage.size.height), [originalImage CGImage]);

CGImageRef bwImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSapce);

UIImage *resultImage = [UIImage imageWithCGImage:bwImage];
CGImageRelease(bwImage);

UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, originalImage.scale);
[resultImage drawInRect:CGRectMake(0.0, 0.0, originalImage.size.width, originalImage.size.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


return newImage;
}

否则您可以使用GPUImage framework

这是一个获得BSD许可的iOS库,可让您将GPU加速滤镜和其他效果应用于图像,实时摄像机视频和电影。

GPUImage framework

可能会帮助你。

答案 2 :(得分:-1)

对于那些感兴趣的人,我创建了一个Swift 3版本的@bHuMiCA解决方案:

extension UIImage {
    var bwImage: UIImage? {
        guard let cgImage = cgImage,
            let bwContext = bwContext else {
                return nil
        }

        let rect = CGRect(origin: .zero, size: size)
        bwContext.draw(cgImage, in: rect)
        let bwCgImage = bwContext.makeImage()

        return bwCgImage.flatMap { UIImage(cgImage: $0) }
    }

    private var bwContext: CGContext? {
        let bwContext = CGContext(data: nil,
                                  width: Int(size.width * scale),
                                  height: Int(size.height * scale),
                                  bitsPerComponent: 8,
                                  bytesPerRow: Int(size.width * scale),
                                  space: CGColorSpaceCreateDeviceGray(),
                                  bitmapInfo: CGImageAlphaInfo.none.rawValue)

        bwContext?.interpolationQuality = .high
        bwContext?.setShouldAntialias(false)

        return bwContext
    }
}