如何调整 UIImage 的大小以减少上传图片的大小 [英] How do I resize the UIImage to reduce upload image size
问题描述
我一直在搜索谷歌,并且只遇到过减少高度/宽度或一些如何通过 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)
")
body.appendString("Content-Disposition: form-data; name="image"; filename="randomName"
")
body.appendString("Content-Type: image/png
")
body.appendData(data)
body.appendString("
")
}
它正在发送 12MB 的照片.我怎样才能将其减少到 1mb?谢谢!
and it's sending 12MB photos. How can I reduce this to 1mb? thanks!
推荐答案
Xcode 9 • Swift 4 或更高版本
编辑/更新:对于 iOS10+ 我们可以使用 UIGraphicsImageRenderer.对于较旧的 Swift 语法,请检查编辑历史记录.
edit/update: For iOS10+ We can use UIGraphicsImageRenderer. For older Swift syntax check edit history.
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)
这篇关于如何调整 UIImage 的大小以减少上传图片的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!