Skip to content

Instantly share code, notes, and snippets.

@oliverbarreto
Created December 19, 2013 20:34
Show Gist options
  • Select an option

  • Save oliverbarreto/8045834 to your computer and use it in GitHub Desktop.

Select an option

Save oliverbarreto/8045834 to your computer and use it in GitHub Desktop.
Create Thumbnail from UIImage To create a thumbnail of a image, we are going to draw a scaled-down version of the full image to an offscreen context and keep a pointer to that new image inside a object instance. You also need a place to store this thumbnail image so that it can be reloaded when the application launches again.
//Declare these 2 properties. The NSData will be a very small chunk of data that conforms to NSCoding protocol so it can be encoded with NSCoder
@property (nonatomic, strong) UIImage *thumbnail;
@property (nonatomic, strong) NSData *thumbnailData;
- (void)setThumbnailDataFromImage:(UIImage *)image
{
    CGSize origImageSize = [image size];
    // The rectangle of the thumbnail
    CGRect newRect = CGRectMake(0, 0, 40, 40);
    // Figure out a scaling ratio to make sure we maintain the same aspect ratio
    float ratio = MAX(newRect.size.width / origImageSize.width,
                      newRect.size.height / origImageSize.height);
    // Create a transparent bitmap context with a scaling factor
    // equal to that of the screen
    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
    // Create a path that is a rounded rectangle
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect
                                                    cornerRadius:5.0];
    // Make all subsequent drawing clip to this rounded rectangle
    [path addClip];
// Center the image in the thumbnail rectangle
    CGRect projectRect;
    projectRect.size.width = ratio * origImageSize.width;
    projectRect.size.height = ratio * origImageSize.height;
    projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
    projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
    // Draw the image on it
    [image drawInRect:projectRect];
    // Get the image from the image context, keep it as our thumbnail
    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
    [self setThumbnail:smallImage];
    // Get the PNG representation of the image and set it as our archivable data
    NSData *data = UIImagePNGRepresentation(smallImage);
    [self setThumbnailData:data];
    // Cleanup image context resources, we're done
    UIGraphicsEndImageContext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment