iOS Swift 图像量化可减少 PNG 图像中的颜色数量

dev*_*dev 5 core-image image-compression ios whatsapp swift

我想将图像中的颜色数量(即 24 位 PNG 文件)减少为较小的 8 位索引彩色图像。

我想通过从图库中选择来在 iOS 设备上创建 WhatsApp 贴纸,因为它允许 512 X 512 像素大小和小于 100k 的文件大小

我已经绑定了这个代码

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
}
Run Code Online (Sandbox Code Playgroud)

并且对于 543KB 的图像只能压缩到 108kb,无法压缩小于此尺寸的图像。所以我需要帮助进行图像量化,以减少 PNG 图像中的颜色数量,而不会丢失 Swift 4.2 中的透明背景。

谢谢

Tam*_*ury 3

您可以从中获取帮助,https://github.com/kosua20/TheQuantizer。有一个名为 rgbaRepresentation() 的函数,它将任何图像转换为较小的 8 位索引彩色图像数据。还有另一个项目https://github.com/iChochy/libminipng也将图像量化为较低位。从我发现的其他项目来看,这两个在 Swift 中运行相对容易。