根据UIImage创建任意大小thumbnail
来源:互联网 发布:网店运维 s5源码下载 编辑:程序博客网 时间:2024/06/15 12:40
+ (UIImage*)thumbnailOfImage:(UIImage*)image withSize:(CGSize)aSize{ //NSLog(@"create thumbnail image"); if (!image) return nil; CGImageRef imageRef = [image CGImage]; UIImage *thumb = nil; // struct CGSize imgSize = [imageRef size]; 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)); // CGContextRotateCTM( bitmap, 180*(M_PI/180)); 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];}