Wednesday, August 17, 2011

Creating an image thumbnail

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
 
// set the image we have chosen to the background of the current view. (OPTIONAL!)
imageView.image  = image;
 
// write the file to the TEMP Directory in the iphone, then when the user has completed
 
 
// selecting their image from the picker, we want to write both the full sized file, and the
 
// thumbnail to the /tmp directory for use later (whatever you want)
 
NSData *pngImage = UIImagePNGRepresentation(image);
 
if([pngImage writeToFile:[NSString stringWithFormat:@"%@/tempImage.png"
TEMP_FOLDER] atomically:YES]){
 
// now that we have saved our image, lets generate a thumbnail from that image, and
// save that one as well.
 
// lets essentially make a copy of the selected image.
 
 
UIImage *myThumbNail    = [[UIImage alloc] initWithData:pngImage];
 
// begin an image context that will essentially "hold" our new image
 
 
UIGraphicsBeginImageContext(CGSizeMake(60.0,60.0));
 
// now redraw our image in a smaller rectangle.
 
 
[myThumbNail drawInRect:CGRectMake(0.0, 0.0, 60.0, 60.0)];

 
// make a "copy" of the image from the current context
 
UIImage *newImage    = UIGraphicsGetImageFromCurrentImageContext();
 
UIGraphicsEndImageContext();
 
// create a new view to place on our screen (OPTIONAL-- testing)
 
UIImageView *thumbView    = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 60.0, 60.0)];
 
thumbView.image    = newImage;
 
[self.view addSubview:thumbView];
 
// now grab the PNG representation of our image
 
NSData    *thumbData    = UIImagePNGRepresentation(newImage);
 
// now finally we can write our new thumbnail to the tmp directory on the phone.
 
 
if([thumbData writeToFile:[NSString stringWithFormat:@"%@/tempImageThumb.png", TEMP_FOLDER] atomically:YES]){
NSLog(@"thumb written!");
}
 
// close the modal view
 
[picker dismissModalViewControllerAnimated:YES];
 
}else{
 
// there was an error writing the image file to the tmp folder....
 
 
NSLog(@" there was an error writing the file to the temp directory");
   }
}

No comments:

Post a Comment