所以我正在做的是反复压缩图像,直到它适合大小框架。它需要多次尝试,放弃,然后我们告诉用户图像太大了。
我的问题是,在图像大小减小后,当它更改为 UIImage 时,它的大小又会变回原样。
这是减小图像大小的代码:
double compressionRatio = 1;
int resizeAttempts = 5;
NSData * imgData = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],compressionRatio);
NSLog(@"Starting Size: %i", [imgData length]);
//Trying to push it below around about 0.4 meg
while ([imgData length] > 400000 && resizeAttempts > 0) {
resizeAttempts -= 1;
NSLog(@"Image was bigger than 400000 Bytes. Resizing.");
NSLog(@"%i Attempts Remaining",resizeAttempts);
//Increase the compression amount
compressionRatio = compressionRatio*0.5;
//Test size before compression
NSLog(@"Current Size: %i",[imgData length]);
imgData = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],compressionRatio);
//Test size after compression
NSLog(@"New Size: %i",[imgData length]);
}
//Set image by comprssed version
savedImage = [UIImage imageWithData:imgData];
//Check how big the image is now its been compressed and put into the UIImageView
NSData *endData = UIImageJPEGRepresentation(savedImage,1.0);
NSLog(@"Ending Size: %i", [endData length]);
好的,现在这是控制台报告:
Starting Image Size: 4076994
Image was bigger than 400000 Bytes. Resizing.
4 Attempts Remaining
Current Size: 4076994
New Compressed Size: 844482
Image was bigger than 400000 Bytes. Resizing.
3 Attempts Remaining
Current Size: 844482
New Compressed Size: 357459
Ending Image Size: 2090332
如您所见,图像从 4mb 开始。它被压缩到 350kb,最后它被制作成一个 UIImage 为 2mb。
提前感谢任何可以理解这一点的人。