Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress/resize image on iOS before uploading to a server?

I'm currently uploading an image to a server using Imgur on iOS with the following code:

NSData* imageData = UIImagePNGRepresentation(image); NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* fullPathToFile = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"SBTempImage.png"]; [imageData writeToFile:fullPathToFile atomically:NO];  [uploadRequest setFile:fullPathToFile forKey:@"image"]; 

The code works fine when run in the simulator and uploading a file from the simulator's photo library because I'm on a fast ethernet connection. However, the same code times out on the iPhone when selecting an image taken with the iPhone. So, I tried it by saving a small image from the web and attempting to upload that, which worked.

This leads me to believe the large images taken by the iPhone are timing out over the somewhat slow 3G network. Is there any way to compress/resize the image from the iPhone before sending it?

like image 798
joshholat Avatar asked Dec 09 '10 03:12

joshholat


People also ask

How do I resize an image before uploading to Wordpress?

Select all the photos on the desktop and double click to open them in the 'Preview' app. Click 'Tools' in the menu bar and choose 'Adjust Size…'. Choose the new size you want in pixels for either width or height and 'Preview' will keep the same dimensions.


1 Answers

This snippet will resize the image:

UIGraphicsBeginImageContext(newSize); [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

The variable newSize is a CGSize and can be defined like so:

CGSize newSize = CGSizeMake(100.0f, 100.0f); 
like image 66
Tuan Nguyen Avatar answered Sep 20 '22 16:09

Tuan Nguyen