0

如何在 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!
}

但尺寸不是我所期望的。

4

2 回答 2

2

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

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

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

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

这个stackoverflow 线程,尤其是这个答案提供了一些提示。

希望能帮助到你。

于 2018-12-14T18:35:18.527 回答
0

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

于 2018-12-27T17:51:46.557 回答