-
Notifications
You must be signed in to change notification settings - Fork 14
/
UIImage+Thumbnail.m
59 lines (41 loc) · 1.57 KB
/
UIImage+Thumbnail.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// UIImage+Thumbnail.m
//
// Created by Cory on 11/04/07.
// Copyright 2011 Cory R. Leach. All rights reserved.
//
#import "UIImage+Thumbnail.h"
@implementation UIImage (Thumbnail)
- (UIImage*) imageWithThumbnailWidth:(CGFloat)thumbnailWidth {
CGFloat width = self.size.width;
CGFloat height = self.size.height;
//Get thumbnail scale
CGFloat scale = thumbnailWidth/width;
//Find dimensions of thumbnail with const aspect ratio
width = thumbnailWidth;
height = self.size.height*scale;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
size_t bitsPerComponent = 8;
size_t bytesPerPixel = 4;
size_t bytesPerRow = bytesPerPixel * width;
size_t totalBytes = bytesPerRow * height;
//Allocate Image space
uint8_t* rawData = malloc(totalBytes);
//Create Bitmap of same size
CGContextRef context = CGBitmapContextCreate(rawData,width,height,bitsPerComponent,bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
//Draw our image to the context
CGContextDrawImage(context, CGRectMake(0, 0, width, height), self.CGImage);
//Create Image
CGImageRef newImg = CGBitmapContextCreateImage(context);
//Release Created Data Structs
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
free(rawData);
//Create UIImage struct around image
UIImage* image = [UIImage imageWithCGImage:newImg];
//Release our hold on the image
CGImageRelease(newImg);
//return new image!
return image;
}
@end