Search code examples
iosswiftuiimageviewpngtransparency

png transparent image metadata coming with white background


The metadata is pulling a transparent png image from a url. However the UIImageView is not coming in as transparent and has a white background.

Is there a work around this issue?

Perhaps .pngData()

@IBOutlet weak var mainCenterIcon: UIImageView!

func initAudioPlayer() {
        
        let url = URL(string: activeAudioURL) 
        let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
        player = AVPlayer(playerItem: playerItem)
        
        //MetaData to recieve album artwork
        let metadataList = playerItem.asset.metadata
        
        
        for item in metadataList {

            guard let key = item.commonKey?.rawValue, let value = item.value else{
                continue
            }

           switch key {
           case "artwork" where value is Data : mainCenterIcon.image = UIImage(data: value as! Data)
            default:
              continue
           }
        }
    }

Solution

  • I have found a solution:

    extension UIImage {
        func imageByMakingWhiteBackgroundTransparent() -> UIImage? {
    
            let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
            let rawImageRef: CGImage = image.cgImage!
    
            let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
            UIGraphicsBeginImageContext(image.size);
    
            let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
            UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
            UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
            UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
            let result = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return result
    
        }
    
    }
    

    To call the function:

    mainCenterIcon.image = UIImage(data: value as! Data)
    mainCenterIcon.image = mainCenterIcon.image!.imageByMakingWhiteBackgroundTransparent()
    

    reference: Original Post