-1

I have a procedure that sends image taken through my iPad app to a database (code below). Is there a way of reducing the size of the image before it is posted?

UIImage *image = [photos objectAtIndex:i];
NSData *imageData = UIImageJPEGRepresentation(image, 10);

// setting up the request object
NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:photoPostString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [photoRequest setHTTPMethod:@"POST"];


NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:photoPostString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[photoRequest setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
photoRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"1234.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[photoRequest setHTTPBody:body];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
RGriffiths
  • 5,722
  • 18
  • 72
  • 120

2 Answers2

2

You can resize UIImage before upload.

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Or some helper Classes:

https://github.com/AliSoftware/UIImage-Resize

https://github.com/mustangostang/UIImage-ResizeMagick

Luan Nguyen
  • 375
  • 3
  • 6
2

https://github.com/AliSoftware/UIImage-Resize

Add this category ("UIImage+Resize.h" & "UIImage+Resize.m") to your project.

UIImage *newImage = [existingImage resizedImageToSize:CGSizeMake(128, 128)];
Babu Lal
  • 136
  • 1
  • 4
  • Thanks. Can it be done by a % so that it works for both landscape and portrait without having to deal with widths and heights separately? – RGriffiths Sep 20 '15 at 14:00