IOS 原生上传图像 体验优化实践

001 问题 在项目中会遇到上传图像体验不好例如图片大上传慢,用户等待很长时间,或者暴力压缩导致图片质量下降 影响后台审核 

002 个人解决案:判断图片是否超过预设大小,在 一个while循环中进行压缩判断直到满足预设大小才上传到服务器 代码如下:

 BOOL flag = [self testImgeData:imgData andImage:first];
    //第一次判断是否需要压缩 800kb
    while (flag) {
        //内循环:压缩图片 直到flag为false 才跳出循环
        UIImage* lastImage = [self scaleImage:first toScale:0.65];
        NSData* imgData = UIImageJPEGRepresentation(lastImage, 1);
        flag = [self testImgeData:imgData andImage:lastImage];
        first = lastImage;
    }


 判断预设大小:NSData 的length是bytes格式需要进行除以1024进行单位转换

- (BOOL)testImgeData:(NSData *)data andImage:(UIImage *)image{
    
    double dataLength = [data length] * 1.0;
    
    NSArray *typeArray = @[@"bytes",@"KB",@"MB",@"GB",@"TB",@"PB", @"EB",@"ZB",@"YB"];
        NSInteger index = 0;
        while (dataLength > 1024) {
            dataLength /= 1024.0;
            index ++;
        }
    NSString *str = [NSString stringWithFormat:@"%.3f %@\n",dataLength,typeArray[index]];
   
    if(index >=2){
        //大于1M
        return YES;
    }
    
    if(index ==1 && dataLength > 850){
        //大于850KB
        return YES;
    }
    
    NSLog(@"str=== 无压缩====%@",str);
    
    return NO;
}

等比压缩算法:通过Grgaphic上下文进行获取到 然后等比绘制图片 

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

保存到相册:查看压缩的图片的清晰度

UIImageWriteToSavedPhotosAlbum(first, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
}

 

上一篇:直播视频app源码,获取视频缩略图


下一篇:iOS加载大量图片出现内存警告而crash掉