2011年8月15日 星期一

由原圖獲取iPhone Photo Library Thumbnail Image的方法

這兩天要給公司完成一個有關相片的話Demo,
所以把以前研究圖片的代碼發上來,
可能有用,加上可以做個筆記,一舉兩得

+ (UIImage*)resizeImage:(UIImage*)image width:(int)width height:(int)height
{
// Create a thumbnail version of the image for the event object.
CGSize size = image.size;
CGSize croppedSize;
CGFloat offsetX = 0.0;
CGFloat offsetY = 0.0;

// check the size of the image, we want to make it
// a square with sides the size of the smallest dimension
if (size.width > size.height)
{
offsetX = (size.height - size.width) / 2;
croppedSize = CGSizeMake(size.height, size.height);
}
else
{
offsetY = (size.width - size.height) / 2;
croppedSize = CGSizeMake(size.width, size.width);
}

// Crop the image before resize
CGRect clippedRect = CGRectMake(offsetX * -1, offsetY * -1, croppedSize.width, croppedSize.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
// Done cropping

// Resize the image
UIGraphicsBeginImageContext(CGSizeMake(width, height));
CGContextRef bitmap = UIGraphicsGetCurrentContext();
// 以下代碼很特別,
// 如果圖片是由於Photo library/UIImagePickerController獲得來的,
// 圖片本身的方向會90度倒轉了,
// 只要設定一下CGContextSetTextMatrix為1.0, 0.0, 0.0, -1.0, 0.0, 0.0就會回復正常
CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(bitmap, transform);
[[UIImage imageWithCGImage:imageRef] drawInRect:CGRectMake(0, 0, width, height)];
UIImage* thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Done Resizing

return thumbnail;
}

沒有留言:

張貼留言