2017-05-08 61 views
0

我想用颜色掩码使JPG图像中的颜色透明,因为当我阅读时,颜色掩码只能用于JPG。SWIFT 3 - CGImage到PNG

此代码适用于应用颜色遮罩并将图像另存为JPG格式,但作为JPG,没有透明度,因此我想将JPG图像转换为PNG图像以保持透明度,但是当我尝试要做到这一点,颜色面具不起作用。

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

这里的2个函数的代码:

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 

} 

感谢你的帮助。

回答

0

感谢DonMag在我的其他问题SWIFT 3 - CGImage copy always nil的问题,这里是解决这一代码:

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) 

    } 

}