The best way to optimize the image before uploading to the server

What is the best way to optimize image weight before uploading it to a server in iOS?

The image can be from the user's image library or directly for the UIPicker camera mode.

I have some requirements: minimum download resolution and desired maximum download size.

Let's say kMaxUploadSize = 50 kB and kMinUploadResolution = 1136 * 640

What am I doing now:

while (UIImageJPEGRepresentation(img,1.0).length > MAX_UPLOAD_SIZE){ img = [self scaleDown:img withFactor:0.1]; } NSData *imageData = UIImageJPEGRepresentation(img,1.0); -(UIImage*)scaleDown:(UIImage*)img withFactor:(float)f{ CGSize newSize = CGSizeMake(img.size.width*f, img.size.height*f); UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0); [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; 

}

The time spent in each cycle is terrible, a few seconds, which leads to a very large delay before efficiently sending the image to the server.

Any approach / idea / strategy?

Thanks a lot!

+4
source share
1 answer

Thanks for your feedback. This is what I decided to do and look great in terms of performance: resizing to the desired resolution, then and only then iteratively compress until it reaches the desired size.

Code example:

 //Resize the image float factor; float resol = img.size.height*img.size.width; if (resol >MIN_UPLOAD_RESOLUTION){ factor = sqrt(resol/MIN_UPLOAD_RESOLUTION)*2; img = [self scaleDown:img withSize:CGSizeMake(img.size.width/factor, img.size.height/factor)]; } //Compress the image CGFloat compression = 0.9f; CGFloat maxCompression = 0.1f; NSData *imageData = UIImageJPEGRepresentation(img, compression); while ([imageData length] > MAX_UPLOAD_SIZE && compression > maxCompression) { compression -= 0.10; imageData = UIImageJPEGRepresentation(img, compression); NSLog(@"Compress : %d",imageData.length); } 

and

 - (UIImage*)scaleDown:(UIImage*)img withSize:(CGSize)newSize{ UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0); [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } 

thanks

+11
source

Source: https://habr.com/ru/post/1498557/


All Articles