Search code examples
iosswiftuiimagepngmp3

Extract Image artwork from MP3 audio data as PNG


I have an image coming in as a JPEG. I need to assign the UIImageView with this data as a png. How can I convert the data to be a PNG by using

.pngData()

My transparent image is showing a white background because it comes in as a JPEG but I need it to come in as a PNG.

@IBOutlet weak var mainCenterIcon: UIImageView!

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

  • If you need to convert the artwork data from JPEG to PNG you just need to initialize an UIImage object and get its png data representation. AFAIK there is no way to add transparent background to a JPEG image. Anyway this is how I would convert from JPEG to PNG data:

    import MediaPlayer
    
    extension Collection where Element == AVMetadataItem {
        var artwork: UIImage? {
            first { $0.commonKey == .commonKeyArtwork }?.dataValue?.image
        }
    }
    

    extension Data {
        var image: UIImage? { UIImage(data: self) }
    }
    

    extension AVPlayerItem {
        var artwork: UIImage? { asset.metadata.artwork }
    }
    

    extension URL {
        var playerItem: AVPlayerItem { .init(url: self) }
    }
    

    let url = Bundle.main.url(forResource: "songName", withExtension: "mp3")!
    url.playerItem.artwork // w 600 h 600
    if let pngData = url.playerItem.artwork?.pngData() {
        pngData  // 605082 bytes
    }