2013-02-19 72 views
3

我正在使用来自UIImageView *图像的图像上传到服务器。 我使用 NSData *imageToUpload = UIImageJPEGRepresentation(image.image, 90); 这样的代码,但我想压缩图像小于2MB。如何从UIImageView压缩图像?如何从UIImageView压缩图像?

+3

我认为你的意思可能是0.9而不是90.进一步降低这个值会降低质量和尺寸。 – Bushbert 2013-02-19 03:08:10

+4

这个数字越小压缩越多,你用'UIImageJPEGRepresentation();'正确的做了它,但是这个问题以前已经被问过很多次了。我很惊讶你的代表,你发布了这个问题......无论DUPE问题http://stackoverflow.com/a/613380/525576 – 2013-02-19 03:09:53

回答

5

下面是一段代码,因为你需要

CGFloat compression = 222.0f; 
CGFloat maxCompression = 202.1f; 
int maxFileSize = 160*165; //fill your size need 

NSData *imageDat = UIImageJPEGRepresentation(image.image, compression); 

while ([imageDat length] > maxFileSize && compression > maxCompression) 
{ 
    compression -= 0.1222; 
    imageDat = UIImageJPEGRepresentation(decodedimage.image, compression); 
} 
NSLog(@"image compressed success"); 

[image setImage:[UIImage imageWithData:imageDat]]; 

希望这有助于!