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)\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")
}
and it's sending 12MB photos. How can I reduce this to 1mb? thanks!
This is what I done in swift 3 for resizing an UIImage. It reduces the image size to less than 100kb. It works proportionally!
Usage:
If you are uploading image in
NSData
format, use this :yourImage
is yourUIImage
.floatvalue
is compression value(0.0 to 1.0)The above is to convert image to
JPEG
.For
PNG
use :UIImagePNGRepresentation
Note : Above code is in Objective-C. Please check how to define NSData in Swift.
This is the way which i followed to resize image.
Using this method my image having 6.5 MB reduced to 104 KB.
Swift 4 code:
Based on the answer of Tung Fam. To resize to a specific file size. Like 0.7 MB you can use this code.
Here is user4261201's answer but in swift, that I am currently using:
Resize the UIImage using .resizeToMaximumBytes