减少png图像的文件大小

Reduce the file size of png image

如何在 Swift.

中将 png 图像的文件大小减小到小于 64KB 并且不丢失透明背景并保持 512 X 512 像素

我试过这个代码:

   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!
}

但是尺寸不是我想要的。

你应该检查 WWDC Session 219 - Image and graphics best practices。它的前三分之一包含有关如何优化图形的有用信息,尤其是内存占用。

提议的方法之一是下采样技术。这是一个片段:

func downsample(imageAt imageURL: URL, to pointSize: CGSize, scale: CGFloat) -> UIImage {
    let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
    let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions)!
    let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
    let downsampleOptions =
            [kCGImageSourceCreateThumbnailFromImageAlways: true,
            kCGImageSourceShouldCacheImmediately: true,
            kCGImageSourceCreateThumbnailWithTransform: true,
            kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
    let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions)!
    return UIImage(cgImage: downsampledImage)
}

下采样将根据下采样大小的变化按比例减少图像内存大小。此外,图像质量和内存占用之间始终存在权衡,结果在很大程度上取决于压缩算法和压缩设置。

, and especially 提供了一些提示。

希望对您有所帮助。

我正在压缩为 WebP 格式,与 PNG 相比,它提供的文件大小大约小 3 倍,因为我要创建 WhatsApp 贴纸包,它也接受 WebP