//循环压缩,知道服务器限制,我这边的限制是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; }