- iPhone Dev tags: - scale - uiimage - uiimagepickercontroller Simply creating a thumbnail image - even from a CameraPicker | Cactus

Simply creating a thumbnail image - even from a CameraPicker

I spent some time researching how to do this on the iPhone, so I figured others would too : The UIImagePickerController gives you a farily large image back ,expecially ith it's the one coming from the camera. You don't want to display that image as it's too big. You usually don't want to send that image. Wwat can you do then? Resize it first. Using a category on UIImage to scale =========================== If you're still a bit fresh on Objective-C, you have just heard about catgories. Now is the time to create one. Add a new UIImage+Scaling class file to your project and add this in the header: `#import ` `@interface UIImage(Scaling)` `- (UIImage *) scaledImageWithWidth:(CGFloat)width andHeight:(CGFloat)height;` `@end` And then implement the scaledImageWithWidth message in the .m file: `- (UIImage *) scaledImageWithWidth:(CGFloat)width andHeight:(CGFloat)height {` ` CGRect rect = CGRectMake(0.0, 0.0, width, height);` ` UIGraphicsBeginImageContext(rect.size);` ` [self drawInRect:rect]; // scales image to rect` ` UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();` ` UIGraphicsEndImageContext();` ` return scaledImage;` `}` This category is making things nice with the CoreGraphics library to create a scaled version of an image in just 6 lines of Code. Now, you can use this in your UIImagePickerController delegates. Using the scaled image ====================== To use this new method of UIImage you just defined, simply add the file to your imports `#import "UIImage+Scaling.h"` ..... And do something with the image when the camera return it to you: `-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{` ` UIImage *thumbnail;` ` float width = image.size.width;` ` float height = image.size.height;` ` if( width < height ){` ` thumbnail = [image scaledImageWithWidth:320.0f andHeight:480.0f];` ` } else {` ` thumbnail = [image scaledImageWithWidth:480.0f andHeight:320.0f];` ` }` ` //DO SOMETHING WITH THE THUMBNAIL` ` [picker dismissModalViewControllerAnimated:YES];` ` …` Do not use the orientation property of the image that is returned to you from the camera. It is useless. Don't use the width and height of the underlying CGImage, as it is always 1200x1600, no matter the orientation. Really use the width and height parameters of the size property. You can use UIImageWriteToSavedPhotosAlbum to save the original image to your photo album too right there.

Publié le 9 Mar 2009
Écrit par Cyril