4

I m taking images from photo library.I have large images of 4-5 mb but i want to compress those images.As i need to store those images in local memory of iphone.for using less memory or for getting less memory warning i need to compress those images.

I don't know how to compress images and videos.So i want to know hot to compress images?

    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSData* data = UIImageJPEGRepresentation(image,1.0);
    NSLog(@"found an image");

    NSString *path = [destinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg", name]];
    [data writeToFile:path atomically:YES]; 

This is the code for saving my image. I dont want to store the whole image as its too big. So, I want to compress it to a much smaller size as I'll need to attach multiple images.

Thanks for the reply.

nids
  • 73
  • 1
  • 3
  • 10
  • 1
    Compressing images won't help you with memory errors. You can compress images to save disk space (flash ram) but if you want to display the images they will always be decompressed in memory and will use width*height*4 ram. – Bastian Mar 19 '12 at 12:23

3 Answers3

13

You can choose a lower quality for JPEG encoding

NSData* data = UIImageJPEGRepresentation(image, 0.8);

Something like 0.8 shouldn't be too noticeable, and should really improve file sizes.

On top of this, look into resizing the image before making the JPEG representation, using a method like this:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Source: The simplest way to resize an UIImage?

Community
  • 1
  • 1
joerick
  • 16,078
  • 4
  • 53
  • 57
  • I think your second point about resizing is very important, and depending upon the situation it can drastically reduce size without sacrificing quality. Especially if you detect an image larger in dimensions than what can be viewed on the screen. Great answer. – Usman Mutawakil Jan 30 '14 at 14:02
5

UIImageJPEGRepresentation(UIImage,Quality);

1.0 means maximum Quality and 0 means minimum quality.

SO change the quality parameter in below line to reduce file size of the image

NSData* data = UIImageJPEGRepresentation(image,1.0);
Krrish
  • 2,256
  • 18
  • 21
1
NSData *UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);

OR

NSData *image_Data=UIImageJPEGRepresentation(image_Name,compressionQuality);

return image as JPEG. May return nil if image has no CGImageRef or invalid bitmap format. compressionQuality is 0(most) & 1(least).

Vaibhav Sharma
  • 1,123
  • 10
  • 22