【问题标题】:Output Fixed-Size JPEG from UIImage从 UIImage 输出固定大小的 JPEG
【发布时间】:2018-05-14 03:39:46
【问题描述】:

我目前正在使用以下代码从 UIImage 对象生成固定大小的 JPEG 图像:

var ratio: CGFloat = 1
var imageData : Data = UIImageJPEGRepresentation(edited, ratio)!

while imageData.count > 200000 {
    if ratio == 0.1 {
        break
    }

    ratio = ratio - 0.1
    imageData = UIImageJPEGRepresentation(edited, ratio)!
}

但是,此代码似乎有点低效,因为我需要不断降低比率,直到图像大小低于指定值 (200 kb)。有没有更好的方法来快速实现这种行为?

【问题讨论】:

  • Dichotomy - 如果大小大于限制,则从 0.5 开始,使用 0.25,如果更小 - 使用 0.75,依此类推
  • 你好,固定大小的 JPEG 图像试试这个LINK 为你的解决方案。

标签: ios swift cocoa-touch uiimage jpeg


【解决方案1】:

使用此扩展程序可以缩小图像尺寸。

extension UIImage {

    func resizeImage(factor: CGFloat) -> UIImage? {
        let newWidth = self.size.width * factor    // Calculate size from factor.
        let newHeight = self.size.height * factor

        let size = CGSize(width: newWidth, height: newHeight)
        return resizeImage(targetSize: size)       // Return image with scaled factor.
    }

    func resizeImage(targetSize: CGSize) -> UIImage? {
        let originalSize = self.size

        let widthRatio = targetSize.width / originalSize.width
        let heightRatio = targetSize.height / originalSize.height
        let ratio = min(widthRatio, heightRatio)

        let newSize = CGSize(width: originalSize.width * ratio, height: originalSize.height * ratio)
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
        self.draw(in: rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage
    }

}

使用它,我们可以使用您上面的代码来实现您想要做的事情。

var imageData: Data = UIImageJPEGRepresentation(edited, 1.0)

while imageData.count < 200000 {
     imageData = UIImageJPEGRepresentation(UIImage(data: imageData)!.resizeImage(factor: 0.9)!, 1.0)
     // imageData will be incremented down each time by a factor of 0.1 (1.0 - ratio)
}

编辑:如果您不想包含扩展,则可以使用 imageData = UIImageJPEGRepresentation(imageData, 0.9),因为它每次仍会缩小 0.1 倍。

【讨论】:

    【解决方案2】:

    您几乎完成了,您可以让extension 以 K-Byte 调整图像大小

    extension UIImage {
        func resizeImageByKByte(kb: Int) {
            let maxByte : Int64 = Int64(kb * 1024)
            var maxCompressQuality: CGFloat = 1
            var imageByte : Int64 = Int64(UIImageJPEGRepresentation(self, 1)?.count ?? 0)
            while imageByte > maxByte {
                imageByte = Int64(UIImageJPEGRepresentation(self, maxCompressQuality)?.count ?? 0)
                maxCompressQuality -= 0.1
            }
        }
    }
    

    这样使用:

     UIImage().resizeImageByKByte(kb: 200) // 200 KB
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2018-07-31
      • 2021-08-13
      • 1970-01-01
      • 2018-09-24
      • 2012-01-04
      • 1970-01-01
      相关资源
      最近更新 更多