ios – 如何调整UIImage的大小以减少上传图片大小

我一直在搜索google,并且只遇到图书馆,减少高度/宽度或一些如何编辑UIImage外观通过CoreImage。但我没有看到或发现一个库,发布,解释如何减少图像大小,所以当它上传时,它不是完整的图像大小。

到目前为止我有这个:

        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?谢谢!

Xcode 8.2.1•Swift 3.0.2

extension UIImage {
    func resized(withPercentage percentage: CGFloat) -> UIImage? {
        let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
        UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: canvasSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    func resized(toWidth width: CGFloat) -> UIImage? {
        let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
        UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
        defer { UIGraphicsEndImageContext() }
        draw(in: CGRect(origin: .zero, size: canvasSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

用法:

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

let myThumb1 = myPicture.resized(withPercentage: 0.1)
let myThumb2 = myPicture.resized(toWidth: 72.0)
http://stackoverflow.com/questions/29137488/how-do-i-resize-the-uiimage-to-reduce-upload-image-size

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ios – 如何调整UIImage的大小以减少上传图片大小