【问题标题】:SWIFT 3 - CGImage to PNGSWIFT 3 - CGImage转PNG
【发布时间】:2017-05-10 04:55:40
【问题描述】:

我正在尝试使用颜色遮罩使 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

}

感谢您的帮助。

【问题讨论】:

    标签: ios swift swift3 cgimage


    【解决方案1】:

    感谢我的另一个问题SWIFT 3 - CGImage copy always nil中的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)
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 2021-12-28
      • 2016-11-14
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多