Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method to resize UIImage is better and why?

To all of you graphics experts, I was wondering which one of these two methods is better for resizing a UIImage:

The first one I've come across is simple and popular and is the following:

-(UIImage *)resizeImage:(UIImage *)image width:(CGFloat)resizedWidth height:(CGFloat)resizedHeight
{
    UIGraphicsBeginImageContext(CGSizeMake(resizedWidth ,resizedHeight));
    [image drawInRect:CGRectMake(0, 0, resizedWidth, resizedHeight)];
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return result;
}

The second method I found at this link http://iphonesdksnippets.com/post/2009/05/06/Resize-image-and-keep-aspect-ratio.aspx and seems to accomplish the same as the above, but is much more intricate (I don't really understand what is going on in it):

-(UIImage *)resizeImage:(UIImage *)image width:(CGFloat)resizedWidth height:(CGFloat)resizedHeight
 {
    CGImageRef imageRef = [image CGImage];

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmap = CGBitmapContextCreate(NULL, resizedWidth, resizedHeight, 8, 4 * resizedWidth, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(bitmap, CGRectMake(0, 0, resizedWidth, resizedHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage *result = [UIImage imageWithCGImage:ref];

    CGContextRelease(bitmap);
    CGImageRelease(ref);

    return result;  
}

So my question is, which way is better and why?

like image 533
Ser Pounce Avatar asked Nov 16 '11 18:11

Ser Pounce


2 Answers

The second one is thread safe.

like image 69
Geri Borbás Avatar answered Nov 16 '22 01:11

Geri Borbás


This is a rather late reply, but I'll just go ahead and add it anyways.

I actually found some behavioral differences between the two methods, besides prestanda.

In an photo app of mine, I have custom camera view that sends any taken image to a custom image editor. In the app, the custom camera/editor views are landscape exclusive. However, the native camera window itself it NOT.

So, whenever a photo happened to be taken in portrait mode, the end result is distorted. These distortions are easily handled by flipping the width and height, whenever width < height.

The first method of the two above methods (the simple one) resulted in an image that was rotated 90 degrees and still distorted. The second, however, resized the image perfectly!

I guess that this has something to do with the graphics context-based behavior. The second method does not use this context, and it works flawlessly in my case.

like image 20
Daniel Saidi Avatar answered Nov 16 '22 01:11

Daniel Saidi