Skip to content

Instantly share code, notes, and snippets.

@hbhargava7
Last active May 22, 2016 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hbhargava7/167336bec4ffc0e13da9aa0bd17fbcd0 to your computer and use it in GitHub Desktop.
Save hbhargava7/167336bec4ffc0e13da9aa0bd17fbcd0 to your computer and use it in GitHub Desktop.
Iteratively optimize and compress UIImage and Convert to Base64 for Server Upload (Objective C).
/* Created by Hersh Bhargava of H2 Micro (www.h2micro.com) */
- (NSString *)compressAndEncodeToBase64String:(UIImage *)image
{
//Scale Image to some width (xFinal)
float ratio = image.size.width/image.size.height;
float xFinal = 700; //Desired image width
float yFinal = xFinal/ratio;
UIImage *scaledImage = [self imageWithImage:image scaledToSize:CGSizeMake(xFinal, yFinal)];
//Compress the image iteratively until either the maximum compression threshold (maxCompression) is reached or the maximum file size requirement is satisfied (maxSize)
CGFloat compression = 1.0f;
CGFloat maxCompression = 0.1f;
float maxSize = 100*1024; //specified in bytes
NSData *imageData = UIImageJPEGRepresentation(scaledImage, compression);
while ([imageData length] > maxSize && compression > maxCompression) {
compression -= 0.10;
imageData = UIImageJPEGRepresentation(scaledImage, compression);
NSLog(@"Compressed to: %.2f MB with Factor: %.2f",(float)imageData.length/1024.0f/1024.0f, compression);
}
NSLog(@"Final Image Size: %.2f MB",(float)imageData.length/1024.0f/1024.0f);
NSString *compressedImageString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]; //Alter options as needed.
return compressedImageString;
}
//This method will decode the base64 string from the above method back into an image.
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData
{
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *final = [UIImage imageWithData:data];
return final;
}
//Ancillary method to scale an image based on a CGSize
- (UIImage *)imageWithImage:(UIImage*)originalImage scaledToSize:(CGSize)newSize;
{
@synchronized(self)
{
UIGraphicsBeginImageContext(newSize);
[originalImage drawInRect:CGRectMake(0,0,newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment