Posted by: Tharindu | April 19, 2010

How to create iPhone Photos like thumbs in an iPhone App

I wanted to create image thumbnails or thumbs of images in an iPhone application. For this I have searched over the web for a small sample code to do this. I have found few but they all didn’t seem to be the right way. They didn’t work perfect as how Apple does it. Some methods introduced distortions and some only scaled the image. Therefore, finally I thought of implementing it my self. It’s actually a very simple algorithm or process to implement. A combination of cropping and scaling in one method.

1. Check UIImage width and height we want to scale first. If both width and height are same no need to crop. If width is bigger then we need to crop image to a ratio of its height. And we determine the xposition to crop the image by subtracting height by its width and then dividing answer by two. The same process done other way if height is bigger than width taking width as the cropping ratio.

2. Now we have a square image that we can scale to our thumb size. This scaling now will not include any distortions to the image.

Below is the code segment that does it nicely.

/** generate thumbnail version of given image to show in properly **/
- (UIImage *)generatePhotoThumbnail:(UIImage *)image withRatio:(float)ratio {
   // first crop to a rectangle and then scale the cropped image to ratio
   CGRect cropRect;
   if (image.size.width == image.size.height) {
      // height and width are same - do not crop here
      cropRect = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
   } else if (image.size.width > image.size.height) {
      // width is longer - take height and adjust xgap to crop
      int xgap = (image.size.width - image.size.height)/2;
      cropRect = CGRectMake(xgap, 0.0, image.size.height, image.size.height);
   } else {
      // height is longer - take height and adjust ygap to crop
      int ygap = (image.size.height - image.size.width)/2;
      cropRect = CGRectMake(0.0, ygap, image.size.width, image.size.width);
   }
   // crop image with calcuted crop rect
   CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
   UIImage *cropped = [UIImage imageWithCGImage:imageRef];
   CGImageRelease(imageRef);
   // scale the image to ratio to create proper thumb
   NSData *pngData = UIImagePNGRepresentation(cropped);
   UIImage *myThumbNail    = [[UIImage alloc] initWithData:pngData];

   // begin an image context that will essentially keep our new image
   UIGraphicsBeginImageContext(CGSizeMake(ratio,ratio));

   // now redraw our image in a smaller rectangle.
   [myThumbNail drawInRect:CGRectMake(0.0, 0.0, ratio, ratio)];

   // make a copy of the image from the current context
   UIImage *newImage    = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   [myThumbNail release];
   return newImage;
}

Leave a comment

Categories