Right now, you have a routine that says:
// Check if the image size is too large
if ((imageData.length/1024) >= 1024) {
while ((imageData.length/1024) >= 1024) {
NSLog(@"While start - The imagedata size is currently: %f KB",roundf((imageData.length/1024)));
// While the imageData is too large scale down the image
// Get the current image size
CGSize currentSize = CGSizeMake(image.size.width, image.size.height);
// Resize the image
image = [image resizedImage:CGSizeMake(roundf(((currentSize.width/100)*80)), roundf(((currentSize.height/100)*80))) interpolationQuality:kMESImageQuality];
// Pass the NSData out again
imageData = UIImageJPEGRepresentation(image, kMESImageQuality);
}
}
I wouldn't advise recursively resizing the image. Every time you resize, you lose some quality (often manifesting itself as a "softening" of the image with loss of detail, with cumulative effects). You always want to go back to original image and resize that smaller and smaller. (As a minor aside, that if
statement is redundant, too.)
I might suggest the following:
NSData *imageData = UIImageJPEGRepresentation(image, kMESImageQuality);
double factor = 1.0;
double adjustment = 1.0 / sqrt(2.0); // or use 0.8 or whatever you want
CGSize size = image.size;
CGSize currentSize = size;
UIImage *currentImage = image;
while (imageData.length >= (1024 * 1024))
{
factor *= adjustment;
currentSize = CGSizeMake(roundf(size.width * factor), roundf(size.height * factor));
currentImage = [image resizedImage:currentSize interpolationQuality:kMESImageQuality];
imageData = UIImageJPEGRepresentation(currentImage, kMESImageQuality);
}
Note, I'm not touching image
, the original image, but rather assigning currentImage
by doing a resize from the original image each time, by a decreasing scale each time.
BTW, if you're wondering about my cryptic 1.0 / sqrt(2.0)
, I was trying to draw a compromise between your iterative 80% factor and my desire to favor resizing by a power of 2 where I can (because a reduction retains more sharpness when done by a power of 2). But use whatever adjustment
factor you want.
Finally, if you're doing this on huge images, you might think about using @autoreleasepool
blocks. You'll want to profile your app in Allocations in Instruments and see where your high water mark is, as in the absence of autorelease pools, this may constitute a fairly aggressive use of memory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…