1、生成指定大小的缩略图
+ (UIImage *)thumbnailWithImage:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image) {
newimage = nil;
}
else{
UIGraphicsBeginImageContext(asize);
[image drawInRect:CGRectMake(0, 0, asize.width, asize.height)];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
2、保持原来的长宽比
+ (UIImage *)thumbnailWithImage:(UIImage *)image sizeScale:(CGSize)sizeScale
{
UIImage *newimage;
if (nil == image) {
newimage = nil;
}
else{
CGSize oldsize = image.size;
CGRect rect;
if (sizeScale.width / sizeScale.height > oldsize.width / oldsize.height) {
rect.size.width = sizeScale.height*oldsize.width/oldsize.height;
rect.size.height = sizeScale.height;
rect.origin.x = (sizeScale.width - rect.size.width) / 2;
rect.origin.y = 0;
}
else{
rect.size.width = sizeScale.width;
rect.size.height = sizeScale.width*oldsize.height/oldsize.width;
rect.origin.x = 0;
rect.origin.y = (sizeScale.height - rect.size.height) / 2;
}
UIGraphicsBeginImageContext(sizeScale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, sizeScale.width, sizeScale.height));//clear background
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}