Rom*_*nge 4 iphone performance upload image ios
在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;
Run Code Online (Sandbox Code Playgroud)
}
每个循环中花费的时间非常多,几秒钟,这导致在将图像有效地发送到服务器之前有很长的延迟.
任何方法/想法/策略?
非常感谢 !
Rom*_*nge 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);
}
Run Code Online (Sandbox Code Playgroud)
和
- (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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢