【问题标题】:swift ios reduce image size before upload [duplicate]swift ios在上传之前减小图像大小[重复]
【发布时间】:2017-04-06 13:01:29
【问题描述】:

在上传图片之前,我正在尝试尽可能减小图片的文件大小。现在我正在这样做:

if let firstImageData = UIImageJPEGRepresentation(pickedImage, 0.1) {  
                                        self.imgArray.append(firstImageData)
}

这将拍摄来自相机或相册的任何图像,将其设为 jpg 并减小其大小。

我已将设置设置为 0.1,但是当我上传图片时,大小仍然在 300-350kb 左右,有什么办法可以将它们调整得更大,我的目标是 50- 70kb

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以先使用这些扩展程序将您的图片调整为较小的尺寸,方法是按百分比或宽度

    调整图片大小
    extension UIImage {
        func resizeWithPercent(percentage: CGFloat) -> UIImage? {
            let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage)))
            imageView.contentMode = .ScaleAspectFit
            imageView.image = self
            UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
            guard let context = UIGraphicsGetCurrentContext() else { return nil }
            imageView.layer.renderInContext(context)
            guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
            UIGraphicsEndImageContext()
            return result
        }
        func resizeWithWidth(width: CGFloat) -> UIImage? {
            let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
            imageView.contentMode = .ScaleAspectFit
            imageView.image = self
            UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
            guard let context = UIGraphicsGetCurrentContext() else { return nil }
            imageView.layer.renderInContext(context)
            guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
            UIGraphicsEndImageContext()
            return result
        }
    }
    

    要使用它,只需像这样调用它

    myImage = myImage.resizeWithWidth(700)!
    

    现在您仍然可以使用您选择的压缩率对其进行压缩

    let compressData = UIImageJPEGRepresentation(myImage, 0.5) //max value is 1.0 and minimum is 0.0
    let compressedImage = UIImage(data: compressData!)
    

    【讨论】:

    • 这似乎有效,但由于某种原因,它使图像看起来很可怕。超级模糊。知道为什么会发生这种情况以及解决方法吗?
    • 将压缩值增加到 0.75 或 0.8 而不是 0.5
    【解决方案2】:

    您只能更改图像的大小(较小的大小 = 较少的数据)并使用 JPEG 等图像压缩算法对其进行压缩,没有其他方法(更好的算法 = 相同质量的较小大小)。

    我听说谷歌最近使用神经网络改进了 JPEG 算法(谷歌的 TensorFlow)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多