Objective-C UIImageをアスペク比を保ったままリサイズ

UIImageのアスペクト比を保ったまま、画像をリサイズする。

引数で渡す、NIIntegerでsizeを指定したサイズ未満に画像をリサイズします。
縦長い画像はheightが、横長画像の場合はがwidthが指定したサイズになります。

参考プログラム
http://stackoverflow.com/questions/1282830/uiimagepickercontroller-uiimage-memory-and-more

#import "ImageResize.h"

@implementation ImageResize

#define radians( degrees ) ( degrees * M_PI / 180 )

+ (UIImage*)resizeAspectFit:(UIImage*)sourceImage size:(NSInteger)size
{
    
    CGImageRef imageRef = [sourceImage CGImage];
    size_t w = CGImageGetWidth(imageRef);
    size_t h = CGImageGetHeight(imageRef);
    CGFloat targetWidth, targetHeight;
    
    if (w>h) {
        targetWidth = size;
        targetHeight = h * targetWidth / w;
    } else {
        targetWidth = size;
        targetHeight = w * targetWidth / h;
    }

    NSLog(@"image resize w=%ld h=%ld -> w=%f h=%f", w, h, targetWidth, targetHeight);

    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
    
    if (bitmapInfo == kCGImageAlphaNone) {
        bitmapInfo = kCGImageAlphaNoneSkipLast;
    }
    
    CGContextRef bitmap;
    
    if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
        bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
        
    } else {
        bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
        
    }   
    
    if (sourceImage.imageOrientation == UIImageOrientationLeft) {
        CGContextRotateCTM (bitmap, radians(90));
        CGContextTranslateCTM (bitmap, 0, -targetHeight);
        
    } else if (sourceImage.imageOrientation == UIImageOrientationRight) {
        CGContextRotateCTM (bitmap, radians(-90));
        CGContextTranslateCTM (bitmap, -targetWidth, 0);
        
    } else if (sourceImage.imageOrientation == UIImageOrientationUp) {
        // NOTHING
    } else if (sourceImage.imageOrientation == UIImageOrientationDown) {
        CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
        CGContextRotateCTM (bitmap, radians(-180.));
    }
    
    CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage* newImage = [UIImage imageWithCGImage:ref];
    
    CGContextRelease(bitmap);
    CGImageRelease(ref);
    
    return newImage; 
}

@end