iosswiftuiimagecore-imageios-stickers

Reduce the file size of png image


How can I reduce the file size of png image to less than 64KB and without losing the transparent background and maintain 512 X 512 pixels in Swift.

I have tried this code:

   func resizeImageOriginalSize(targetSize: CGSize) -> UIImage {
    var actualHeight: Float = Float(self.size.height)
    var actualWidth: Float = Float(self.size.width)
    let maxHeight: Float = Float(targetSize.height)
    let maxWidth: Float = Float(targetSize.width)
    var imgRatio: Float = actualWidth / actualHeight
    let maxRatio: Float = maxWidth / maxHeight
    var compressionQuality: Float = 0.5
    //50 percent compression

    if actualHeight > maxHeight || actualWidth > maxWidth {
        if imgRatio < maxRatio {
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight
            actualWidth = imgRatio * actualWidth
            actualHeight = maxHeight
        }
        else if imgRatio > maxRatio {
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth
            actualHeight = imgRatio * actualHeight
            actualWidth = maxWidth
        }
        else {
            actualHeight = maxHeight
            actualWidth = maxWidth
            compressionQuality = 0.4
        }
    }
    let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
    UIGraphicsBeginImageContextWithOptions(rect.size, false, CGFloat(compressionQuality))
    self.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()



    UIGraphicsEndImageContext()
    return newImage!
}

but size is not what I expected.


Solution

  • I'm compressing to WebP formate which providing around 3X smaller file sizes compared to PNG as I'm to create WhatsApp sticker pack, which also accepts WebP