¿Cómo cambio el tamaño del UIImage para reducir el tamaño de la imagen de carga?

He estado buscando en google y solo he encontrado bibliotecas que reducen el alto / ancho o cómo se edita el aspecto del UIImage a través de CoreImage. Pero no he visto ni encontrado una biblioteca, publicación que explique cómo reducir el tamaño de la imagen para que cuando se cargue no sea el tamaño completo de la imagen.

hasta ahora tengo esto:

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") } 

y está enviando fotos de 12MB. ¿Cómo puedo reducir esto a 1mb? ¡Gracias!

Xcode 8.2.1 • Swift 3.0.2

 extension UIImage { func resized(withPercentage percentage: CGFloat) -> UIImage? { let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } func resized(toWidth width: CGFloat) -> UIImage? { let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } } 

Uso:

 let myPicture = UIImage(data: try! Data(contentsOf: URL(string:"http://sofes.miximages.com/ios/Xs4RX.jpg")!))! let myThumb1 = myPicture.resized(withPercentage: 0.1) let myThumb2 = myPicture.resized(toWidth: 72.0) 

Esta es la manera que seguí para cambiar el tamaño de la imagen.

  -(UIImage *)resizeImage:(UIImage *)image { float actualHeight = image.size.height; float actualWidth = image.size.width; float maxHeight = 300.0; float maxWidth = 400.0; float imgRatio = actualWidth/actualHeight; float maxRatio = maxWidth/maxHeight; float compressionQuality = 0.5;//50 percent compression if (actualHeight > maxHeight || actualWidth > maxWidth) { if(imgRatio < maxRatio) { //adjust width according to maxHeight imgRatio = maxHeight / actualHeight; actualWidth = imgRatio * actualWidth; actualHeight = maxHeight; } else if(imgRatio > maxRatio) { //adjust height according to maxWidth imgRatio = maxWidth / actualWidth; actualHeight = imgRatio * actualHeight; actualWidth = maxWidth; } else { actualHeight = maxHeight; actualWidth = maxWidth; } } CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight); UIGraphicsBeginImageContext(rect.size); [image drawInRect:rect]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality); UIGraphicsEndImageContext(); return [UIImage imageWithData:imageData]; } 

Usando este método, mi imagen tiene 6.5 MB reducido a 104 KB.

Código de Swift 4:

 func resize(_ image: UIImage) -> UIImage { var actualHeight = Float(image.size.height) var actualWidth = Float(image.size.width) let maxHeight: Float = 300.0 let maxWidth: Float = 400.0 var imgRatio: Float = actualWidth / actualHeight let maxRatio: Float = maxWidth / maxHeight let compressionQuality: Float = 0.5 //50 percent compression if actualHeight > maxHeight || actualWidth > maxWidth { if imgRatio < maxRatio { //adjust width according to maxHeight imgRatio = maxHeight / actualHeight actualWidth = imgRatio * actualWidth actualHeight = maxHeight } else if imgRatio > maxRatio { //adjust height according to maxWidth imgRatio = maxWidth / actualWidth actualHeight = imgRatio * actualHeight actualWidth = maxWidth } else { actualHeight = maxHeight actualWidth = maxWidth } } let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight)) UIGraphicsBeginImageContext(rect.size) image.draw(in: rect) let img = UIGraphicsGetImageFromCurrentImageContext() let imageData = UIImageJPEGRepresentation(img!, CGFloat(compressionQuality)) UIGraphicsEndImageContext() return UIImage(data: imageData!) ?? UIImage() } 

En caso de que alguien esté buscando cambiar el tamaño de la imagen a menos de 1MB con Swift 3 y 4 .

Solo copie y pegue esta extensión:

 extension UIImage { func resized(withPercentage percentage: CGFloat) -> UIImage? { let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage) UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: .zero, size: canvasSize)) return UIGraphicsGetImageFromCurrentImageContext() } func resizedTo1MB() -> UIImage? { guard let imageData = UIImagePNGRepresentation(self) else { return nil } var resizingImage = self var imageSizeKB = Double(imageData.count) / 1000.0 // ! Or devide for 1024 if you need KB but not kB while imageSizeKB > 1000 { // ! Or use 1024 if you need KB but not kB guard let resizedImage = resizingImage.resized(withPercentage: 0.9), let imageData = UIImagePNGRepresentation(resizedImage) else { return nil } resizingImage = resizedImage imageSizeKB = Double(imageData.count) / 1000.0 // ! Or devide for 1024 if you need KB but not kB } return resizingImage } } 

Y uso:

 let resizedImage = originalImage.resizedTo1MB() 

lo mismo que Leo Answer, pero pequeñas ediciones para SWIFT 2.0

  extension UIImage { func resizeWithPercentage(percentage: CGFloat) -> UIImage? { let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: size.width * percentage, height: size.height * percentage))) imageView.contentMode = .ScaleAspectFit imageView.image = self UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.renderInContext(context) guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return result } func resizeWithWidth(width: CGFloat) -> UIImage? { let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))))) imageView.contentMode = .ScaleAspectFit imageView.image = self UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.renderInContext(context) guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil } UIGraphicsEndImageContext() return result } } 

Aquí está la respuesta del usuario4261201 pero de forma rápida, que actualmente estoy usando:

 func compressImage (_ image: UIImage) -> UIImage { let actualHeight:CGFloat = image.size.height let actualWidth:CGFloat = image.size.width let imgRatio:CGFloat = actualWidth/actualHeight let maxWidth:CGFloat = 1024.0 let resizedHeight:CGFloat = maxWidth/imgRatio let compressionQuality:CGFloat = 0.5 let rect:CGRect = CGRect(x: 0, y: 0, width: maxWidth, height: resizedHeight) UIGraphicsBeginImageContext(rect.size) image.draw(in: rect) let img: UIImage = UIGraphicsGetImageFromCurrentImageContext()! let imageData:Data = UIImageJPEGRepresentation(img, compressionQuality)! UIGraphicsEndImageContext() return UIImage(data: imageData)! } 

Si está cargando una imagen en formato NSData , use esto:

 NSData *imageData = UIImageJPEGRepresentation(yourImage, floatValue); 

yourImage es tu UIImage . floatvalue es el valor de compresión (0.0 a 1.0)

Lo anterior es para convertir la imagen a JPEG .

Para el uso de PNG : UIImagePNGRepresentation

Nota: El código anterior está en Objective-C. Por favor, compruebe cómo definir NSData en Swift.

Esto es lo que hice en swift 3 para cambiar el tamaño de un UIImage. Reduce el tamaño de la imagen a menos de 100 kb. ¡Funciona proporcionalmente!

 extension UIImage { class func scaleImageWithDivisor(img: UIImage, divisor: CGFloat) -> UIImage { let size = CGSize(width: img.size.width/divisor, height: img.size.height/divisor) UIGraphicsBeginImageContext(size) img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } } 

Uso:

 let scaledImage = UIImage.scaleImageWithDivisor(img: capturedImage!, divisor: 3) 

Cambia el tamaño del UIImage usando .resizeToMaximumBytes