向服务器上传图片的时候,如果图片大小超过服务器限制,需要对图片进行压缩,下面是压缩方法

时间:2024-02-25 21:33:41
   //循环压缩,知道服务器限制,我这边的限制是2MB
     for (int i = 0; i < 10; i++) {
        imageData = UIImagePNGRepresentation(img);
        if (imageData.length > 2*1000*1000) {
            img = [LDUnity compressImageWith:img];
            NSLog(@"第%d次压缩 === %lu",i,(unsigned long)imageData.length);
            continue;
        } else {
            NSLog(@"%lu",(unsigned long)imageData.length);
            break;
        }
    }

 

//修改图片大小
+ (UIImage *) compressImageWith:(UIImage*)image {
    CGSize newSize;
    newSize.height = image.size.height*0.8;
    newSize.width  = image.size.width*0.8;
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;
}