iOS实现图片压缩的两种方法及图片压缩上传功能
两种压缩图片的方法:压缩图片质量(quality),压缩图片尺寸(size)。
压缩图片质量
nsdata *data = uiimagejpegrepresentation(image, compression); uiimage *resultimage = [uiimage imagewithdata:data];
通过 uiimage 和 nsdata 的相互转化,减小 jpeg 图片的质量来压缩图片。uiimagejpegrepresentation:: 第二个参数 compression 取值 0.0~1.0,值越小表示图片质量越低,图片文件自然越小。
压缩图片尺寸
uigraphicsbeginimagecontext(size); [image drawinrect:cgrectmake(0, 0, size.width, size.height)]; resultimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext();
给定所需的图片尺寸 size,resultimage 即为原图 image 绘制为 size 大小的图片。
压缩图片使图片文件小于指定大小
如果对图片清晰度要求不高,要求图片的上传、下载速度快的话,上传图片前需要压缩图片。压缩到什么程度要看具体情况,但一般会设定一个图片文件最大值,例如 100 kb。可以用上诉两种方法来压缩图片。假设图片转化来的 nsdata 对象为 data,通过data.length即可得到图片的字节大小。
压缩图片质量
比较容易想到的方法是,通过循环来逐渐减小图片质量,直到图片稍小于指定大小(maxlength)。
+ (uiimage *)compressimagequality:(uiimage *)image tobyte:(nsinteger)maxlength { cgfloat compression = 1; nsdata *data = uiimagejpegrepresentation(image, compression); while (data.length > maxlength && compression > 0) { compression -= 0.02; data = uiimagejpegrepresentation(image, compression); // when compression less than a value, this code dose not work } uiimage *resultimage = [uiimage imagewithdata:data]; return resultimage; }
这样循环次数多,效率低,耗时长。
可以通过二分法来优化。
+ (uiimage *)compressimagequality:(uiimage *)image tobyte:(nsinteger)maxlength { cgfloat compression = 1; nsdata *data = uiimagejpegrepresentation(image, compression); if (data.length < maxlength) return image; cgfloat max = 1; cgfloat min = 0; for (int i = 0; i < 6; ++i) { compression = (max + min) / 2; data = uiimagejpegrepresentation(image, compression); if (data.length < maxlength * 0.9) { min = compression; } else if (data.length > maxlength) { max = compression; } else { break; } } uiimage *resultimage = [uiimage imagewithdata:data]; return resultimage; }
当图片大小小于 maxlength,大于 maxlength * 0.9 时,不再继续压缩。最多压缩 6 次,1/(2^6) = 0.015625 < 0.02,也能达到每次循环 compression 减小 0.02 的效果。这样的压缩次数比循环减小 compression 少,耗时短。需要注意的是,当图片质量低于一定程度时,继续压缩没有效果。也就是说,compression 继续减小,data 也不再继续减小。压缩图片质量的优点在于,尽可能保留图片清晰度,图片不会明显模糊;缺点在于,不能保证图片压缩后小于指定大小。
压缩图片尺寸
与之前类似,比较容易想到的方法是,通过循环逐渐减小图片尺寸,直到图片稍小于指定大小(maxlength)。具体代码省略。同样的问题是循环次数多,效率低,耗时长。可以用二分法来提高效率,具体代码省略。这里介绍另外一种方法,比二分法更好,压缩次数少,而且可以使图片压缩后刚好小于指定大小(不只是 < maxlength, > maxlength * 0.9)。
+ (uiimage *)compressimagesize:(uiimage *)image tobyte:(nsuinteger)maxlength { uiimage *resultimage = image; nsdata *data = uiimagejpegrepresentation(resultimage, 1); nsuinteger lastdatalength = 0; while (data.length > maxlength && data.length != lastdatalength) { lastdatalength = data.length; cgfloat ratio = (cgfloat)maxlength / data.length; cgsize size = cgsizemake((nsuinteger)(resultimage.size.width * sqrtf(ratio)), (nsuinteger)(resultimage.size.height * sqrtf(ratio))); // use nsuinteger to prevent white blank uigraphicsbeginimagecontext(size); // use image to draw (drawinrect:), image is larger but more compression time // use result image to draw, image is smaller but less compression time [resultimage drawinrect:cgrectmake(0, 0, size.width, size.height)]; resultimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext(); data = uiimagejpegrepresentation(resultimage, 1); } return resultimage; }
[resultimage drawinrect:cgrectmake(0, 0, size.width, size.height)];
是用新图 resultimage 绘制,也可以用原图 image 来绘制。用原图绘制,压缩后图片更接近指定大小,但是压缩次数较多,耗时较长。一张大小为 6064 kb 的图片,压缩图片尺寸,原图绘制与新图绘制结果如下
指定大小(kb) | 原图绘制压缩后大小(kb) | 原图绘制压缩次数 | 新图绘制压缩后大小(kb) | 新图绘制压缩次数 |
---|---|---|---|---|
500 | 498 | 6 | 498 | 3 |
300 | 299 | 4 | 296 | 3 |
100 | 99 | 5 | 98 | 3 |
50 | 49 | 6 | 48 | 3 |
两种绘制方法压缩后大小很接近,与指定大小也很接近,但原图绘制压缩次数可达到新图绘制压缩次数的两倍。建议使用新图绘制,减少压缩次数。压缩后图片明显比压缩质量模糊。
需要注意的是绘制尺寸的代码
cgsize size = cgsizemake((nsuinteger)(resultimage.size.width * sqrtf(ratio)), (nsuinteger)(resultimage.size.height * sqrtf(ratio)));,
每次绘制的尺寸 size,要把宽 width 和 高 height 转换为整数,防止绘制出的图片有白边。
压缩图片尺寸可以使图片小于指定大小,但会使图片明显模糊(比压缩图片质量模糊)。
两种图片压缩方法结合
如果要保证图片清晰度,建议选择压缩图片质量。如果要使图片一定小于指定大小,压缩图片尺寸可以满足。对于后一种需求,还可以先压缩图片质量,如果已经小于指定大小,就可得到清晰的图片,否则再压缩图片尺寸。
+ (uiimage *)compressimage:(uiimage *)image tobyte:(nsuinteger)maxlength { // compress by quality cgfloat compression = 1; nsdata *data = uiimagejpegrepresentation(image, compression); if (data.length < maxlength) return image; cgfloat max = 1; cgfloat min = 0; for (int i = 0; i < 6; ++i) { compression = (max + min) / 2; data = uiimagejpegrepresentation(image, compression); if (data.length < maxlength * 0.9) { min = compression; } else if (data.length > maxlength) { max = compression; } else { break; } } uiimage *resultimage = [uiimage imagewithdata:data]; if (data.length < maxlength) return resultimage; // compress by size nsuinteger lastdatalength = 0; while (data.length > maxlength && data.length != lastdatalength) { lastdatalength = data.length; cgfloat ratio = (cgfloat)maxlength / data.length; cgsize size = cgsizemake((nsuinteger)(resultimage.size.width * sqrtf(ratio)), (nsuinteger)(resultimage.size.height * sqrtf(ratio))); // use nsuinteger to prevent white blank uigraphicsbeginimagecontext(size); [resultimage drawinrect:cgrectmake(0, 0, size.width, size.height)]; resultimage = uigraphicsgetimagefromcurrentimagecontext(); uigraphicsendimagecontext(); data = uiimagejpegrepresentation(resultimage, compression); } return resultimage; }
下面看下ios图片压缩上传的实现方法
需求
很多时候我们上传图片经常遇到一些问题,要不就是图片质量变差,要不就是图片太大等等问题。这里,我找到了一个算是目前比较符合需求的解决方案。在原有基础上增加了动态压缩系数,改写成swift版本。
实现思路
先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后再根据图片最终大小来设置压缩比,比如传入maxsize = 30kb,最终计算大概这个大小的压缩比。基本上最终出来的图片数据根据当前分辨率能保持差不多的大小同时不至于太模糊,跟微信,微博最终效果应该是差不多的,代码仍然有待优化!
实现代码
swift3.0之前旧版本压缩模式
// mark: - 降低质量 func resetsizeofimagedata(source_image: uiimage, maxsize: int) -> nsdata { //先调整分辨率 var newsize = cgsize(width: source_image.size.width, height: source_image.size.height) let tempheight = newsize.height / 1024 let tempwidth = newsize.width / 1024 if tempwidth > 1.0 && tempwidth > tempheight { newsize = cgsize(width: source_image.size.width / tempwidth, height: source_image.size.height / tempwidth) } else if tempheight > 1.0 && tempwidth < tempheight { newsize = cgsize(width: source_image.size.width / tempheight, height: source_image.size.height / tempheight) } uigraphicsbeginimagecontext(newsize) source_image.drawaspatterninrect(cgrect(x: 0, y: 0, width: newsize.width, height: newsize.height)) let newimage = uigraphicsgetimagefromcurrentimagecontext() uigraphicsendimagecontext() //先判断当前质量是否满足要求,不满足再进行压缩 var finallimagedata = uiimagejpegrepresentation(newimage,1.0) let sizeorigin = int64((finallimagedata?.length)!) let sizeoriginkb = int(sizeorigin / 1024) if sizeoriginkb <= maxsize { return finallimagedata! } //保存压缩系数 let compressionqualityarr = nsmutablearray() let avg = cgfloat(1.0/250) var value = avg for var i = 250; i>=1; i-- { value = cgfloat(i)*avg compressionqualityarr.addobject(value) } //调整大小 //说明:压缩系数数组compressionqualityarr是从大到小存储。 //思路:折半计算,如果中间压缩系数仍然降不到目标值maxsize,则从后半部分开始寻找压缩系数;反之从前半部分寻找压缩系数 finallimagedata = uiimagejpegrepresentation(newimage, cgfloat(compressionqualityarr[125] as! nsnumber)) if int(int64((uiimagejpegrepresentation(newimage, cgfloat(compressionqualityarr[125] as! nsnumber))?.length)!)/1024) > maxsize { //拿到最初的大小 finallimagedata = uiimagejpegrepresentation(newimage, 1.0) //从后半部分开始 for idx in 126..<250 { let value = compressionqualityarr[idx] let sizeorigin = int64((finallimagedata?.length)!) let sizeoriginkb = int(sizeorigin / 1024) print("当前降到的质量:\(sizeoriginkb)") if sizeoriginkb > maxsize { print("\(idx)----\(value)") finallimagedata = uiimagejpegrepresentation(newimage, cgfloat(value as! nsnumber)) } else { break } } } else { //拿到最初的大小 finallimagedata = uiimagejpegrepresentation(newimage, 1.0) //从前半部分开始 for idx in 0..<125 { let value = compressionqualityarr[idx] let sizeorigin = int64((finallimagedata?.length)!) let sizeoriginkb = int(sizeorigin / 1024) print("当前降到的质量:\(sizeoriginkb)") if sizeoriginkb > maxsize { print("\(idx)----\(value)") finallimagedata = uiimagejpegrepresentation(newimage, cgfloat(value as! nsnumber)) } else { break } } } return finallimagedata! }
swift3.0版本二分法压缩模式
// mark: - 降低质量 func resetsizeofimagedata(source_image: uiimage!, maxsize: int) -> nsdata { //先判断当前质量是否满足要求,不满足再进行压缩 var finallimagedata = uiimagejpegrepresentation(source_image,1.0) let sizeorigin = finallimagedata?.count let sizeoriginkb = sizeorigin! / 1024 if sizeoriginkb <= maxsize { return finallimagedata! as nsdata } //先调整分辨率 var defaultsize = cgsize(width: 1024, height: 1024) let newimage = self.newsizeimage(size: defaultsize, source_image: source_image) finallimagedata = uiimagejpegrepresentation(newimage,1.0); //保存压缩系数 let compressionqualityarr = nsmutablearray() let avg = cgfloat(1.0/250) var value = avg var i = 250 repeat { i -= 1 value = cgfloat(i)*avg compressionqualityarr.add(value) } while i >= 1 /* 调整大小 说明:压缩系数数组compressionqualityarr是从大到小存储。 */ //思路:使用二分法搜索 finallimagedata = self.halffuntion(arr: compressionqualityarr.copy() as! [cgfloat], image: newimage, sourcedata: finallimagedata!, maxsize: maxsize) //如果还是未能压缩到指定大小,则进行降分辨率 while finallimagedata?.count == 0 { //每次降100分辨率 if defaultsize.width-100 <= 0 || defaultsize.height-100 <= 0 { break } defaultsize = cgsize(width: defaultsize.width-100, height: defaultsize.height-100) let image = self.newsizeimage(size: defaultsize, source_image: uiimage.init(data: uiimagejpegrepresentation(newimage, compressionqualityarr.lastobject as! cgfloat)!)!) finallimagedata = self.halffuntion(arr: compressionqualityarr.copy() as! [cgfloat], image: image, sourcedata: uiimagejpegrepresentation(image,1.0)!, maxsize: maxsize) } return finallimagedata! as nsdata } // mark: - 调整图片分辨率/尺寸(等比例缩放) func newsizeimage(size: cgsize, source_image: uiimage) -> uiimage { var newsize = cgsize(width: source_image.size.width, height: source_image.size.height) let tempheight = newsize.height / size.height let tempwidth = newsize.width / size.width if tempwidth > 1.0 && tempwidth > tempheight { newsize = cgsize(width: source_image.size.width / tempwidth, height: source_image.size.height / tempwidth) } else if tempheight > 1.0 && tempwidth < tempheight { newsize = cgsize(width: source_image.size.width / tempheight, height: source_image.size.height / tempheight) } uigraphicsbeginimagecontext(newsize) source_image.draw(in: cgrect(x: 0, y: 0, width: newsize.width, height: newsize.height)) let newimage = uigraphicsgetimagefromcurrentimagecontext() uigraphicsendimagecontext() return newimage! } // mark: - 二分法 func halffuntion(arr: [cgfloat], image: uiimage, sourcedata finallimagedata: data, maxsize: int) -> data? { var tempfinallimagedata = finallimagedata var tempdata = data.init() var start = 0 var end = arr.count - 1 var index = 0 var difference = int.max while start <= end { index = start + (end - start)/2 tempfinallimagedata = uiimagejpegrepresentation(image, arr[index])! let sizeorigin = tempfinallimagedata.count let sizeoriginkb = sizeorigin / 1024 print("当前降到的质量:\(sizeoriginkb)\n\(index)----\(arr[index])") if sizeoriginkb > maxsize { start = index + 1 } else if sizeoriginkb < maxsize { if maxsize-sizeoriginkb < difference { difference = maxsize-sizeoriginkb tempdata = tempfinallimagedata } end = index - 1 } else { break } } return tempdata }
以上所述是小编给大家介绍的ios实现图片压缩的两种方法,希望对大家有所帮助