如何使用Core Image

时间:2018-12-21 07:39:46

标签: swift uiimage rgb core-image

我正在寻找解决方案,以在不更改分辨率和尺寸的情况下向图像应用色调。我正在使用RGB值和CIColorControls创建自定义滤镜。我可以应用不同的颜色控件(即亮度,对比度和饱和度)。

我有价值观, 对比度,亮度,饱和度为(110%。,110%,130%) 而且我已经很好地应用了它。到目前为止,这是我的代码:

func applyCustomValues(image: UIImage, brightness: Double, contrast: Double, saturation: Double) -> UIImage{

    let beginImage = CIImage(cgImage: image.cgImage!)
    let parameters = [
        "inputContrast": NSNumber(value: contrast),
        "inputBrightness": NSNumber(value: brightness),
        "inputSaturation": NSNumber(value: saturation),
        ]
    let outputImage = beginImage.applyingFilter("CIColorControls", parameters: parameters)

    let context = CIContext(options: nil)

    let outputCGImage = context.createCGImage(outputImage, from: outputImage.extent)

    return UIImage(cgImage: outputCGImage)
}

我的RGB值分别为R = 243,G = 106,B = 188。

我想将所有这些值应用到图像上,并希望像要求一样输出

应用色调(RGB),这是我到目前为止的代码:

func tint(image: UIImage, color: UIColor) -> UIImage
{
    let ciImage = CIImage(image: image)
    let filter = CIFilter(name: "CIMultiplyCompositing")
    filter?.setDefaults()

    let colorFilter = CIFilter(name: "CIConstantColorGenerator")
    let ciColor = CIColor(color: color)
    colorFilter?.setValue(ciColor, forKey: kCIInputColorKey)
    let colorImage = colorFilter?.outputImage

    filter?.setValue(colorImage, forKey: kCIInputImageKey)
    filter?.setValue(ciImage, forKey: kCIInputBackgroundImageKey)
    let context = CIContext(options: nil)
    let cgImage = context.createCGImage(filter!.outputImage!, from: (ciImage?.extent)!)
    return UIImage(cgImage: cgImage!)
}

要应用Tint和CIColorControls,

   let tintImage = tint(image:orinalImage, color: UIColor.getTintColor(r: 255/255, g: 131/255, b: 0/255, alpha: 1))

   let colorControlImage = applyCustomValues(image: tintImage, brightness: 0.11, contrast: 1.10, saturation: 1.3)

它返回在下面粘贴的输出图像

enter image description here

原始图片是

enter image description here

预期的输出图像 Please ignore the scale of image 请忽略图像的比例

请纠正我,如果我错了,实现此目的的正确方法是什么。

1 个答案:

答案 0 :(得分:0)

最后,我得到了想要的答案,希望它对某人有所帮助。

func colorized(with color: UIColor) -> UIImage? {
    guard
        let ciimage = CIImage(image: self),
        let colorMatrix = CIFilter(name: "CIColorMatrix")
        else { return nil }
    var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
    color.getRed(&r, green: &g, blue: &b, alpha: &a)
    colorMatrix.setDefaults()
    colorMatrix.setValue(ciimage, forKey: "inputImage")
    colorMatrix.setValue(CIVector(x: r, y: 0, z: 0, w: 0), forKey: "inputRVector")
    colorMatrix.setValue(CIVector(x: 0, y: g, z: 0, w: 0), forKey: "inputGVector")
    colorMatrix.setValue(CIVector(x: 0, y: 0, z: b, w: 0), forKey: "inputBVector")
    colorMatrix.setValue(CIVector(x: 0, y: 0, z: 0, w: a), forKey: "inputAVector")
    if let ciimage = colorMatrix.outputImage {
        return UIImage(ciImage: ciimage)
    }
    return nil
}