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!
Image resize function in swift as below. func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image. size let widthRatio = targetSize. width / size.
Assuming that you are referring to the layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
Xcode 9 • Swift 4 or later
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)) } } }
Usage:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With