SWIFT 3 - CGImage 转 PNG

SWIFT 3 - CGImage to PNG

我正在尝试使用颜色蒙版使 JPG 图像中的颜色透明,因为据我所知,颜色蒙版仅适用于 JPG。

当我应用颜色蒙版并将图像保存为 JPG 时,此代码有效,但作为 JPG,没有透明度,所以我想将 JPG 图像转换为 PNG 图像以保持透明度,但是当我试试看,颜色遮罩不起作用。

我是不是做错了什么,或者这不是正确的方法。

这是两个函数的代码:

func callChangeColorByTransparent(_ sender: UIButton){

    var colorMasking: [CGFloat] = []
    if let textLabel = sender.titleLabel?.text {

        switch textLabel {
        case "Remove Black":
            colorMasking = [0,30,0,30,0,30]
            break
        case "Remove Red":
            colorMasking = [180,255,0,50,0,60]
            break
        default:
            colorMasking = [222,255,222,255,222,255]
        }
    }

    print(colorMasking)

    let newImage = changeColorByTransparent(selectedImage, colorMasking: colorMasking)
    symbolImageView.image = newImage
}


func changeColorByTransparent(_ image : UIImage, colorMasking : [CGFloat]) -> UIImage {

    let rawImage: CGImage = (image.cgImage)!

    //let colorMasking: [CGFloat] = [222,255,222,255,222,255]

    UIGraphicsBeginImageContext(image.size)

    let maskedImageRef: CGImage = rawImage.copy(maskingColorComponents: colorMasking)!

    if let context = UIGraphicsGetCurrentContext() {

        context.draw(maskedImageRef, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))

        var newImage = UIImage(cgImage: maskedImageRef, scale: image.scale, orientation: image.imageOrientation)

        UIGraphicsEndImageContext()

        var pngImage = UIImage(data: UIImagePNGRepresentation(newImage)!, scale: 1.0)

        return pngImage!
    }

    print("fail")
    return image

}

感谢您的帮助。

感谢 DonMag 在我的另一个问题 中的问题,这里是解决这个问题的代码:

func saveImageWithAlpha(theImage: UIImage, destFile: URL) -> Void {

    // odd but works... solution to image not saving with proper alpha channel
    UIGraphicsBeginImageContext(theImage.size)
    theImage.draw(at: CGPoint.zero)
    let saveImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    if let img = saveImage, let data = UIImagePNGRepresentation(img) {

        try? data.write(to: destFile)

    }

}