Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reduce Image quality/size in iPhone objective-c?

I have an app that lets the user take a picture with his/her iPhone and use it as a background image for the app. I use UIImagePickerController to let the user take a picture and set the background UIImageView image to the returned UIImage object.

IBOutlet UIImageView *backgroundView;

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
 backgroundView.image = image;
 [self dismissModalViewControllerAnimated:YES];
}

This all works fine. How can I reduce the size of the UIImage to 480x320 so my app can be memory efficient? I don't care if I loose any image quality.

Thanks in advance.

like image 872
cduck Avatar asked Jan 17 '10 00:01

cduck


3 Answers

You can create a graphics context, draw the image into that at the desired scale, and use the returned image. For example:

UIGraphicsBeginImageContext(CGSizeMake(480,320));

CGContextRef            context = UIGraphicsGetCurrentContext();

[image drawInRect: CGRectMake(0, 0, 480, 320)];

UIImage        *smallImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();    
like image 91
Ben Gottlieb Avatar answered Jan 11 '23 15:01

Ben Gottlieb


I know this question is already solved, but just if someone (like i did) wants to scale the image keeping the aspect ratio, this code might be helpful:

-(UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)size
{
    float width = size.width;
    float height = size.height;

    UIGraphicsBeginImageContext(size);
    CGRect rect = CGRectMake(0, 0, width, height);

    float widthRatio = image.size.width / width;
    float heightRatio = image.size.height / height; 
    float divisor = widthRatio > heightRatio ? widthRatio : heightRatio;

    width = image.size.width / divisor; 
    height = image.size.height / divisor;

    rect.size.width  = width;
    rect.size.height = height;

    if(height < width)
        rect.origin.y = height / 3;

    [image drawInRect: rect];

    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();   

    return smallImage;
}
like image 29
Kai Avatar answered Jan 11 '23 17:01

Kai


Use contentOfFile and make sure that all of your images are .png. Apple is optimized for png.

Oh, use the contentOfFile not the imageName method. Several reasons for that. Images that is brought in memory by ImageName remained in memory even after a [release] is called.

Dont ask my why. The apple told me so.

Roydell Clarke

like image 27
roydell Clarke Avatar answered Jan 11 '23 16:01

roydell Clarke