5

I want to reduce the number of colors in image i.e., 24-bit PNG files to smaller 8-bit indexed color images.

I want to create WhatsApp stickers on the iOS device by picking from gallery, as it allowed 512 X 512 pixels size and less then 100k file size

I have tied this code

func resizeImageWith(image: UIImage, newSize: CGSize) -> UIImage {

    let horizontalRatio = newSize.width / image.size.width
    let verticalRatio = newSize.height / image.size.height

    let ratio = max(horizontalRatio, verticalRatio)
    let newSize = CGSize(width: image.size.width * ratio, height: image.size.height * ratio)
    var newImage: UIImage
    let renderFormat = UIGraphicsImageRendererFormat.default()
        renderFormat.opaque = false
    if #available(iOS 12.0, *) {
        renderFormat.preferredRange = .standard
    } else {
        // Fallback on earlier versions
    }

        renderFormat.scale = 0.5
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
        newImage = renderer.image {
            (context) in

            image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        }


    return newImage
}

and able to compress till 108kb only for 543KB Image, unable to compress less than that. so I want help to do Image Quantization which reduce the number of colors in PNG Images without losing the transparent background in Swift 4.2.

Thanks

dev
  • 87
  • 1
  • 5

1 Answers1

2

You can take help from this, https://github.com/kosua20/TheQuantizer. There is a function named rgbaRepresentation() which converts any image into smaller 8-bit indexed color image data. There is another project https://github.com/iChochy/libminipng which also quantizes the images to lower bits. These two are comparatively easy to run in Swift from other projects I have found.