第一種:系統自帶壓縮方式
NSData * __nullable UIImageJPEGRepresentation(UIImage * __nonnull image, CGFloat compressionQuality)
用法:NSData *dataImage = UIImageJPEGRepresentation(image, 0.1);
當然也有很多人用這種方式image轉data
優點:在基本沒有降低圖片的質量的前提下,壓縮圖片,不改變圖片的分辨率
缺點:壓縮圖片有一定限度,因為這是不改變分辨率的壓縮。比如你想壓縮圖片到原來的十分之一大小,但是他最大可能只會壓縮到三分之一。經測試圖片最大能壓到的大小和圖片本身有關,每個圖片各不相同
第二種:通過改變圖片尺寸壓縮圖片
//壓縮圖片
+ (UIImage*)imageWithImage:(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(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
這個方法我寫成一個UIImage的分類,方便使用
優點:可以縮小圖片到任意大小,可以自定義壓縮后圖片的尺寸
缺點:改變圖片的分辨率,會大大降低圖片的質量