I've been following this excellent resource here: http://stackoverflow.com/questions/1282830/uiimagepickercontroller-uiimage-memory-and-more
and based some of my code off it. But can't seem to get my head around how to accomplish what I want to do.
Basically, I want to take any image from the iPhone (landscape or portrait) and display it at screen resolution (480 x 320). At the moment, I'm scaling images to the width (320) which is working almost fine with portrait images (I'm getting a bit of stretching because of the difference in aspect ratio to the 1600 x 1200 image the camera takes). Also, with the landscape images, these are far too short - they don't fill they screen.
Is there a way I can crop and scale a 320 x 480 section from a landscape image - from the middle of the image.
Here is how I'm calling my method
image = [ImageManipulator imageWithImage:image scaledToSize:CGSizeMake(480,320)];
And below is my method:
+ (UIImage*)imageWithImage:(UIImage*)sourceImage scaledToSize:(CGSize)targetSize {
NSLog(@"Scaling image");
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
if (targetWidth <=sourceImage.size.width && targetHeight <= sourceImage.size.height)
{
CGImageRef imageRef = [sourceImage CGImage];
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;
}
else {
NSLog(@"Finished scaling image");
return sourceImage;
}
NSLog(@"Finished scaling image");
return sourceImage;
}