Search code examples
iosswiftswift3cgimage

SWIFT 3 - CGImage to PNG


I am trying to use a color mask to make a color in JPG image transparent because as I read, color mask only works with JPG.

This code work when I apply the color mask and save the image as a JPG, but as a JPG, there is no transparency so I want to transform the JPG image to a PNG image to keep the transparency but when I try to do it, the color mask doesn't work.

Am I doing something wrong or maybe this isn't the right approach.

Here is the code of the 2 functions :

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

}

Thank for your help.


Solution

  • Thanks the issue of DonMag in my other question SWIFT 3 - CGImage copy always nil, here is the code to solve this :

    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)
    
        }
    
    }