IOS中修改圖片的大小:修改分辨率和裁剪
在IOS開發中,經常有限制圖片文件大小的,有的用戶圖片很大,導致上傳時間慢,造成問題。
如:微信分享中,如果圖片的大小好像大于50kbytes,就分享失敗,而且沒有任何提示。
所以,我添加了兩個函數:
一、修改當前圖片的大小,newSize是新的size尺寸,這個方法幫助用戶獲取到更小的圖片。
但是這個newSize的尺寸建議跟原圖一樣,不然圖片就變形了。
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(,,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
二、截圖功能,實現用戶想要截取圖的RECT
- (UIImage *)getImageByCuttingImage:(UIImage *)image Rect:(CGRect)rect{
//大圖bigImage
//定義myImageRect,截圖的區域
CGRect myImageRect = rect;
UIImage* bigImage= image;
CGImageRef imageRef = bigImage.CGImage;
CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
CGSize size;
size.width = rect.size.width;
size.height = rect.size.height;
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, myImageRect, subImageRef);
UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImage;
}