直接上代码
// 缩略图功能 - (UIImage*)thumbnailOfImage:(UIImage*)image withSize:(CGSize)aSize { //NSLog(@"create thumbnail image"); if (!image) return nil; CGImageRef imageRef = [image CGImage]; UIImage *thumb = nil; float _width = CGImageGetWidth(imageRef); float _height = CGImageGetHeight(imageRef); // hardcode width and height for now, shouldn't stay like that float _resizeToWidth; float _resizeToHeight; _resizeToWidth = aSize.width; _resizeToHeight = aSize.height; float _moveX = 0.0f; float _moveY = 0.0f; // determine the start position in the window if it doesn't fit the sizes 100% //NSLog(@" width: %f to: %f", _width, _resizeToWidth); //NSLog(@" height: %f to: %f", _height, _resizeToHeight); // resize the image if it is bigger than the screen only if ( (_width > _resizeToWidth) || (_height > _resizeToHeight) ) { float _amount = 0.0f; if (_width > _resizeToWidth) { _amount = _resizeToWidth / _width; _width *= _amount; _height *= _amount; //NSLog(@"1 width: %f height: %f", _width, _height); } if (_height > _resizeToHeight) { _amount = _resizeToHeight / _height; _width *= _amount; _height *= _amount; //NSLog(@"2 width: %f height: %f", _width, _height); } } _width = (NSInteger)_width; _height = (NSInteger)_height; _resizeToWidth = _width; _resizeToHeight = _height; CGContextRef bitmap = CGBitmapContextCreate(NULL, _resizeToWidth, _resizeToHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBitsPerPixel(imageRef)*_resizeToWidth, CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef) ); // now center the image _moveX = (_resizeToWidth - _width) / 2; _moveY = (_resizeToHeight - _height) / 2; CGContextSetRGBFillColor(bitmap, 1.f, 1.f, 1.f, 1.0f); CGContextFillRect( bitmap, CGRectMake(0, 0, _resizeToWidth, _resizeToHeight)); CGContextDrawImage( bitmap, CGRectMake(_moveX, _moveY, _width, _height), imageRef ); // create a templete imageref. CGImageRef ref = CGBitmapContextCreateImage( bitmap ); thumb = [UIImage imageWithCGImage:ref]; // release the templete imageref. CGContextRelease( bitmap ); CGImageRelease( ref ); return [[thumb retain] autorelease]; } // 等比例缩放 - (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize { UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize)); [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)]; UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; }