UIImage的縮小
有時候,項目中,要用到上傳圖片,從圖片庫裡取出的圖片有的太大了,而要上傳的時候,會很費時間,而且也沒必要太大,所以就把圖片綜縮小一下,再傳!
[cpp]
#pragma UIImagePickerDelagate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self.imagePopoverController dismissPopoverAnimated:YES];
/*
選取成功後在界面上進行顯示
*/
//壓縮圖片
int iWidth = image.size.width;
int iHeight = image.size.height;
if (iWidth>300) {//300你自定義大小,想要弄多大,就弄多大
iWidth = 300;
iHeight = image.size.height*iWidth/image.size.width;
if (iHeight>300) {
iHeight = 300;
iWidth = image.size.width*iHeight/image.size.height;
}
}
image = [self scaleToSize:image :CGSizeMake(iWidth, iHeight)];//主要在這裡
NSData* imageData = UIImagePNGRepresentation(image);
[self saveImage:imageData WithName:@"pic.jpg"];//保存圖片
}
#pragma UIImagePickerDelagate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self.imagePopoverController dismissPopoverAnimated:YES];
/*
選取成功後在界面上進行顯示
*/
//壓縮圖片
int iWidth = image.size.width;
int iHeight = image.size.height;
if (iWidth>300) {//300你自定義大小,想要弄多大,就弄多大
iWidth = 300;
iHeight = image.size.height*iWidth/image.size.width;
if (iHeight>300) {
iHeight = 300;
iWidth = image.size.width*iHeight/image.size.height;
}
}
image = [self scaleToSize:image :CGSizeMake(iWidth, iHeight)];//主要在這裡
NSData* imageData = UIImagePNGRepresentation(image);
[self saveImage:imageData WithName:@"pic.jpg"];//保存圖片
}
[cpp]
//圖片縮放
- (UIImage *)scaleToSize:(UIImage *)image :(CGSize)newsize {
// 創建一個bitmap的context
// 並把它設置成為當前正在使用的context
UIGraphicsBeginImageContext(newsize);
// 繪制改變大小的圖片
[image drawInRect:CGRectMake(0, 0, newsize.width, newsize.height)];
// 從當前context中創建一個改變大小後的圖片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當前的context出堆棧
UIGraphicsEndImageContext();
// 返回新的改變大小後的圖片
return scaledImage;
}
//圖片縮放
- (UIImage *)scaleToSize:(UIImage *)image :(CGSize)newsize {
// 創建一個bitmap的context
// 並把它設置成為當前正在使用的context
UIGraphicsBeginImageContext(newsize);
// 繪制改變大小的圖片
[image drawInRect:CGRectMake(0, 0, newsize.width, newsize.height)];
// 從當前context中創建一個改變大小後的圖片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當前的context出堆棧
UIGraphicsEndImageContext();
// 返回新的改變大小後的圖片
return scaledImage;
}