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