Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compressing image taken from device or chosen from library, iOS

In my app, user is allowed to take a photo from a device or upload it from the library to set it as his profile pic. Now when user is done, I need to upload that image to server. Usually the image taken from device is of size 5-6MB. I need it to compress to 25KB before uploading to server. So I am using following method to that

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];
    [picker release];
    profilePicImageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSData* pngData = UIImagePNGRepresentation(profilePicImageView.image);
    NSLog(@"image size of png is %d", [pngData length]);
    NSData *imageData = UIImageJPEGRepresentation(profilePicImageView.image, 0.00001);
    NSLog(@"image size is %d", [imageData length]);
}

Problem with this method is, no matter how small I set the scaling parameter, compressed file size does not drop below ~230KB, which is nearly 10 times higher than what I need.

What is wrong with the above method? Can't I compress image to 25KB?

Any help, suggestion will be greatly appreciated.

like image 201
chatur Avatar asked Feb 21 '23 23:02

chatur


1 Answers

Here is an alternative answer, and I think it is a lot more concise. It is from another answer on stack overflow but has been in my code for a while. I am getting ~15kB size images and this is with a resize from standard image taken with camera on 4s (2.5k by 3.5k pixels) to a more useful resolution: (400 by 600). Then compression UIImageJPEGRepresentation(pic,0.1).

CGRect rect = CGRectMake(0,0,capturedImage.size.width/6,capturedImage.size.height/6);
UIGraphicsBeginImageContext( rect.size );
[capturedImage drawInRect:rect];
UIImage *picture1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

NSData *imageDataForResize = UIImageJPEGRepresentation(picture1,0.1);
UIImage *img=[UIImage imageWithData:imageDataForResize];
capturedImage = img; // reassigning to original image as to prevent changing things later in the code

Thanks! I hope this helps other people! This issue is important when you are trying to do QUICK collection view loads where images are loaded from a server.

like image 94
Michael Lorenzo Avatar answered Feb 23 '23 13:02

Michael Lorenzo