如何调整UIImage的大小以减少上传图像大小 [英] How do I resize the UIImage to reduce upload image size
本文介绍了如何调整UIImage的大小以减少上传图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在搜索谷歌,并且只遇到了可以降低高度/宽度的库或者通过CoreImage编辑UIImage外观的库。但我没有看到或找到一个图书馆,帖子解释了如何减少图像尺寸,所以当它上传时,它不是完整的图像尺寸。
I've been searching google, and have only come across libraries that either reduce the height/width or some how edit the UIImage appearance via CoreImage. But I have not seen or found one library, post that explains how to reduce image size so when it uploads, it's not the full image size.
到目前为止我有这个:
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?谢谢!
and it's sending 12MB photos. How can I reduce this to 1mb? thanks!
推荐答案
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)
这篇关于如何调整UIImage的大小以减少上传图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文