上传时压缩图像 [英] Compress image at the time of uploading

查看:170
本文介绍了上传时压缩图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在服务器上传图片。
但在上传之前,我想压缩该图像,然后上传到服务器。我不想上传超过2 MB的图像。
我已经使用过这个逻辑但是如果图像大小很大那么它就不会运行。在处理期间,循环和占用的内存增加到1 gb。

I want to upload image on server. But before uploading i want to compress that image and then upload to server. I dont want to upload image more than 2 mb. I have used this logic but if image size is to large then it runs no. of loops and also occupied memory increased to 1 gb during processing.

 double compressionRatio=1;
 NSData *imgData=UIImagePNGRepresentation(proImage.image,compressionRatio);
   while ([imgData length]>50000) {
    compressionRatio=compressionRatio*50;
    imgData=UIImageJPEGRepresentation(proImage.image,compressionRatio);
   }


推荐答案

请看看< a href =https://developer.apple.com/library/iOS/documentation/UIKit/Reference/UIKitFunctionReference/Reference/reference.html#//apple_ref/doc/uid/TP40006894-CH3-SW9\"rel =nofollow > UIImageJPEGRepresentation文档。

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality
);

compressionQuality = 0.0; ... max compression
compressionQuality = 1.0; ... min compression

您可以尝试类似:

NSData *imgData=UIImagePNGRepresentation(proImage.image,compressionRatio);

if ([NSData length] > maxSizeThatYouWant) {

    CGFloat compressionNeeded = (CGFloat)[NSData length]/(CGFloat)maxSizeThatYouWant;

    imgData=UIImageJPEGRepresentation(proImage.image,compressionNeeded);
}

这篇关于上传时压缩图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆