一尘不染

如何调整UIImage的大小以减小上传图像的大小

swift

我一直在搜索google,只遇到过降低高度/宽度或通过CoreImage如何编辑UIImage外观的库。但是我还没有看到或找到一个库,这篇文章解释了如何减小图像大小,因此在上载时,它不是完整的图像大小。

到目前为止,我有这个:

        if image != nil {
        //let data = NSData(data: UIImagePNGRepresentation(image))
        let data = UIImagePNGRepresentation(image)
        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"image\"; filename=\"randomName\"\r\n")
        body.appendString("Content-Type: image/png\r\n\r\n")
        body.appendData(data)
        body.appendString("\r\n")
    }

并且正在发送12MB的照片。如何将其减小到1mb?谢谢!


阅读 242

收藏
2020-07-07

共1个答案

一尘不染

Xcode 9•Swift 4或更高版本

编辑/更新:对于iOS10
+,我们可以使用UIGraphicsImageRenderer。对于较早的Swift语法,请检查编辑历史记录。

extension UIImage {
    func resized(withPercentage percentage: CGFloat, isOpaque: Bool = true) -> UIImage? {
        let canvas = CGSize(width: size.width * percentage, height: size.height * percentage)
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: canvas, format: format).image {
            _ in draw(in: CGRect(origin: .zero, size: canvas))
        }
    }
    func resized(toWidth width: CGFloat, isOpaque: Bool = true) -> UIImage? {
        let canvas = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: canvas, format: format).image {
            _ in draw(in: CGRect(origin: .zero, size: canvas))
        }
    }
}

用法:

let image = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!

let thumb1 = image.resized(withPercentage: 0.1)
let thumb2 = image.resized(toWidth: 72.0)
2020-07-07