问题描述
我一直在搜索谷歌,并且只遇到过降低高度/宽度或通过 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.
到目前为止,我有这个:
so far I have this:
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 的大小以减小上传图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!