将UIImage压缩到特定大小(以兆字节为单位) [英] Compress UIImage to certain size in megabytes

查看:582
本文介绍了将UIImage压缩到特定大小(以兆字节为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

obj-с如何获得存储在自定义<$ c中的某个 UIImage $ c> NSMutableArray ?这是我想做的第一件事。第二个是,知道图像的文件大小(比如说它是15 MB)比我自己的文件大小限制(说它是5 MB)如何压缩图像是最接近的文件大小限制,说4.99 MB?

In obj-с how does one get the size of a certain UIImage stored in a custom NSMutableArray? That's the first thing I want to do. And the second is, knowing that the image is bigger in file size (say it's 15 MB) than my own file size limit (say it's 5 MB) how does one compress the image to be the closest to the file size limit, say 4.99 MB?

推荐答案

我已经看到这个在stacj溢出链接的另一个问题是 - 按大小压缩图片 - iPhone SDK

i have seen this on another question on stacj overflow link is -- image compression by size - iPhone SDK

但我会组合两个答案从那里,我也使用这个代码做压缩。

but i does combine two answer from there , i also used this code to do compression.

CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

一种方法是在循环中重新压缩文件,直到找到所需的大小。你可以先找到高度和宽度,然后猜测压缩系数(更大的图像更多的压缩),然后压缩它,检查大小,并再次分割差异。

One way to do it, is to re-compress the file in a loop, until you find the desired size. You could first find height and width, and guess the compression factor (larger image more compression) then after you compress it, check the size, and split the difference again.

我知道这不是超级高效,但我不相信有一个单一的调用来实现一个特定大小的图像。

I know this is not super efficient, but I do not believe there is a single call to achieve a image of a specific size.

这篇关于将UIImage压缩到特定大小(以兆字节为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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