4

在将图像上传到 iOS 的服务器之前优化图像权重的最佳做法是什么?

图像可以来自用户的图像库或直接用于 UIPicker - 相机模式。

我确实有一些要求:最小上传分辨率和希望的最大上传大小。

假设 kMaxUploadSize = 50 kB 和 kMinUploadResolution = 1136 * 640

我目前做的是:

while (UIImageJPEGRepresentation(img,1.0).length > MAX_UPLOAD_SIZE){
    img = [self scaleDown:img withFactor:0.1];
}
NSData *imageData = UIImageJPEGRepresentation(img,1.0);

-(UIImage*)scaleDown:(UIImage*)img withFactor:(float)f{

CGSize newSize = CGSizeMake(img.size.width*f, img.size.height*f);

UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
[img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return scaledImage;

}

每个循环花费的时间非常多,几秒钟,这导致在有效地将图像发送到服务器之前有很长的延迟。

任何方法/想法/策略?

非常感谢 !

4

1 回答 1

11

感谢您的反馈。这是我决定做的并且在性能方面很棒:调整到所需的分辨率,然后然后才进行迭代压缩,直到达到所需的大小。

一些示例代码:

//Resize the image 
float factor;
float resol = img.size.height*img.size.width;
if (resol >MIN_UPLOAD_RESOLUTION){
    factor = sqrt(resol/MIN_UPLOAD_RESOLUTION)*2;
    img = [self scaleDown:img withSize:CGSizeMake(img.size.width/factor, img.size.height/factor)];
}

//Compress the image
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;

NSData *imageData = UIImageJPEGRepresentation(img, compression);

while ([imageData length] > MAX_UPLOAD_SIZE && compression > maxCompression)
{
    compression -= 0.10;
    imageData = UIImageJPEGRepresentation(img, compression);
    NSLog(@"Compress : %d",imageData.length);
}

- (UIImage*)scaleDown:(UIImage*)img withSize:(CGSize)newSize{
    UIGraphicsBeginImageContextWithOptions(newSize, YES, 0.0);
    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage; 
}

谢谢

于 2013-08-23T13:45:05.637 回答