views:

2150

answers:

3

Hello !
In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390) interpolationQuality:1];

It works perfectly, but it's an undocumented function, so I can't use it anymore with iPhone OS4.

So... what is the simplest way to resize an UIImage ?
Thanks !

+2  A: 

The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options.

Or you can use this utility method, if you actually need to resize an image:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}
Paul Lynch
I would NOT retain the result here. `newImage` will be autoreleased already, and it should up to the method that called this to retain it or not. This approach is just begging for a memory bug since `init` is not part of the method name. I would expect a method named like this to return an autoreleased object.
Squeegy
Valid point, and edited. I'll just leave the caution that my code that uses this generates malloc errors elsewhere without an additional retain, which is clearly my fault somehow :-).
Paul Lynch
Note that using UIGraphicsBeginImageContext is not thread-safe
Oded Ben Dov
+5  A: 

Trevor Howard has some UIImage categories that handle resize quite nicely. If nothing else you can use the code as examples.

TechZen
+1 for the link. This blog post by Trevor Howard should be bookmarked by everybody.
bddckr
+3  A: 

I've also seen this done as well (which I use on UIButtons for Normal and Selected state since buttons don't resize to fit). Credit goes to whoever the original author was.

First make an empty .h and .m file called UIImageResizing.h and UIImageResizing.c

// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end

// Put this in UIImageResizing.m
@implementation UIImage (Resizing)

- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);

CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return scaledImage;
}

@end

Include that .h file in whatever .m file you're going to use the function in and then call it like this:

UIImage* image = [UIImage imageName:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];
iWasRobbed