圖片去除背景顏色,使背景變爲透明

問題

手寫簽名時,保存的圖片背景是白色的,而且是jpg格式的。後臺希望是一張背景爲透明的簽名圖片,以便合成簽名文件。

思路

JPG不支持透明,PNG才支持

首先任務拆分,分爲兩步:
格式轉換:將JPG轉爲PNG
去除背景:去除PNG的底色

步驟

1、將JPG轉爲PNG
if let data = image.pngData(),
    let pngImage = UIImage.init(data: data) {
    print(pngImage)
}

去除底部顏色

對 UIImage 進行擴展,增加了處理白色背景與黑色背景的方法,調用後自動返回個背景透明的 UIImage

extension UIImage {
    //返回一個將白色背景變透明的UIImage
    func imageByRemoveWhiteBg() -> UIImage? {
        let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
        return transparentColor(colorMasking: colorMasking)
    }
     
    //返回一個將黑色背景變透明的UIImage
    func imageByRemoveBlackBg() -> UIImage? {
        let colorMasking: [CGFloat] = [0, 32, 0, 32, 0, 32]
        return transparentColor(colorMasking: colorMasking)
    }
     
    func transparentColor(colorMasking:[CGFloat]) -> UIImage? {
        if let rawImageRef = self.cgImage {
            UIGraphicsBeginImageContext(self.size)
            if let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking) {
                let context: CGContext = UIGraphicsGetCurrentContext()!
                context.translateBy(x: 0.0, y: self.size.height)
                context.scaleBy(x: 1.0, y: -1.0)
                context.draw(maskedImageRef, in: CGRect(x:0, y:0, width:self.size.width,
                                                        height:self.size.height))
                let result = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                return result
            }
        }
        return nil
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章