Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I resize the UIImage to reduce upload image size

Tags:

ios

swift

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)\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!

like image 861
Jay Avatar asked Mar 19 '15 05:03

Jay


People also ask

How do I make an image smaller in Swift?

Image resize function in swift as below. func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image. size let widthRatio = targetSize. width / size.

How do I make an image smaller in Xcode?

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.


1 Answers

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) 
like image 85
Leo Dabus Avatar answered Oct 11 '22 23:10

Leo Dabus