欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS實(shí)現(xiàn)圖片壓縮的兩種方法及圖片壓縮上傳功能

 更新時(shí)間:2017年01月29日 10:13:08   作者:Silence_cnblogs  
ios 圖片壓縮有兩種方法,分別是,壓縮圖片質(zhì)量(Quality),壓縮圖片尺寸(Size),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下

兩種壓縮圖片的方法:壓縮圖片質(zhì)量(Quality),壓縮圖片尺寸(Size)。

壓縮圖片質(zhì)量

NSData *data = UIImageJPEGRepresentation(image, compression);
UIImage *resultImage = [UIImage imageWithData:data];

通過 UIImage 和 NSData 的相互轉(zhuǎn)化,減小 JPEG 圖片的質(zhì)量來壓縮圖片。UIImageJPEGRepresentation:: 第二個(gè)參數(shù) compression 取值 0.0~1.0,值越小表示圖片質(zhì)量越低,圖片文件自然越小。

壓縮圖片尺寸

UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

給定所需的圖片尺寸 size,resultImage 即為原圖 image 繪制為 size 大小的圖片。

壓縮圖片使圖片文件小于指定大小

如果對(duì)圖片清晰度要求不高,要求圖片的上傳、下載速度快的話,上傳圖片前需要壓縮圖片。壓縮到什么程度要看具體情況,但一般會(huì)設(shè)定一個(gè)圖片文件最大值,例如 100 KB??梢杂蒙显V兩種方法來壓縮圖片。假設(shè)圖片轉(zhuǎn)化來的 NSData 對(duì)象為 data,通過data.length即可得到圖片的字節(jié)大小。

壓縮圖片質(zhì)量

比較容易想到的方法是,通過循環(huán)來逐漸減小圖片質(zhì)量,直到圖片稍小于指定大小(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;
}

這樣循環(huán)次數(shù)多,效率低,耗時(shí)長。

可以通過二分法來優(yōu)化。

+ (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;
}

當(dāng)圖片大小小于 maxLength,大于 maxLength * 0.9 時(shí),不再繼續(xù)壓縮。最多壓縮 6 次,1/(2^6) = 0.015625 < 0.02,也能達(dá)到每次循環(huán) compression 減小 0.02 的效果。這樣的壓縮次數(shù)比循環(huán)減小 compression 少,耗時(shí)短。需要注意的是,當(dāng)圖片質(zhì)量低于一定程度時(shí),繼續(xù)壓縮沒有效果。也就是說,compression 繼續(xù)減小,data 也不再繼續(xù)減小。壓縮圖片質(zhì)量的優(yōu)點(diǎn)在于,盡可能保留圖片清晰度,圖片不會(huì)明顯模糊;缺點(diǎn)在于,不能保證圖片壓縮后小于指定大小。

壓縮圖片尺寸

與之前類似,比較容易想到的方法是,通過循環(huán)逐漸減小圖片尺寸,直到圖片稍小于指定大小(maxLength)。具體代碼省略。同樣的問題是循環(huán)次數(shù)多,效率低,耗時(shí)長??梢杂枚址▉硖岣咝?,具體代碼省略。這里介紹另外一種方法,比二分法更好,壓縮次數(shù)少,而且可以使圖片壓縮后剛好小于指定大小(不只是 < 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 來繪制。用原圖繪制,壓縮后圖片更接近指定大小,但是壓縮次數(shù)較多,耗時(shí)較長。一張大小為 6064 KB 的圖片,壓縮圖片尺寸,原圖繪制與新圖繪制結(jié)果如下

指定大小(KB) 原圖繪制壓縮后大小(KB) 原圖繪制壓縮次數(shù) 新圖繪制壓縮后大小(KB) 新圖繪制壓縮次數(shù)
500 498 6 498 3
300 299 4 296 3
100 99 5 98 3
50 49 6 48 3

兩種繪制方法壓縮后大小很接近,與指定大小也很接近,但原圖繪制壓縮次數(shù)可達(dá)到新圖繪制壓縮次數(shù)的兩倍。建議使用新圖繪制,減少壓縮次數(shù)。壓縮后圖片明顯比壓縮質(zhì)量模糊。

需要注意的是繪制尺寸的代碼

CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio)));,每次繪制的尺寸 size,要把寬 width 和 高 height 轉(zhuǎn)換為整數(shù),防止繪制出的圖片有白邊。

壓縮圖片尺寸可以使圖片小于指定大小,但會(huì)使圖片明顯模糊(比壓縮圖片質(zhì)量模糊)。

兩種圖片壓縮方法結(jié)合

如果要保證圖片清晰度,建議選擇壓縮圖片質(zhì)量。如果要使圖片一定小于指定大小,壓縮圖片尺寸可以滿足。對(duì)于后一種需求,還可以先壓縮圖片質(zhì)量,如果已經(jīng)小于指定大小,就可得到清晰的圖片,否則再壓縮圖片尺寸。

+ (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圖片壓縮上傳的實(shí)現(xiàn)方法

需求

很多時(shí)候我們上傳圖片經(jīng)常遇到一些問題,要不就是圖片質(zhì)量變差,要不就是圖片太大等等問題。這里,我找到了一個(gè)算是目前比較符合需求的解決方案。在原有基礎(chǔ)上增加了動(dòng)態(tài)壓縮系數(shù),改寫成Swift版本。

實(shí)現(xiàn)思路

先調(diào)整分辨率,分辨率可以自己設(shè)定一個(gè)值,大于的就縮小到這分辨率,小余的就保持原本分辨率。然后再根據(jù)圖片最終大小來設(shè)置壓縮比,比如傳入maxSize = 30KB,最終計(jì)算大概這個(gè)大小的壓縮比?;旧献罱K出來的圖片數(shù)據(jù)根據(jù)當(dāng)前分辨率能保持差不多的大小同時(shí)不至于太模糊,跟微信,微博最終效果應(yīng)該是差不多的,代碼仍然有待優(yōu)化!

實(shí)現(xiàn)代碼

Swift3.0之前舊版本壓縮模式

// MARK: - 降低質(zhì)量
 func resetSizeOfImageData(source_image: UIImage, maxSize: Int) -> NSData {
  //先調(diào)整分辨率
  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()
  //先判斷當(dāng)前質(zhì)量是否滿足要求,不滿足再進(jìn)行壓縮
  var finallImageData = UIImageJPEGRepresentation(newImage,1.0)
  let sizeOrigin  = Int64((finallImageData?.length)!)
  let sizeOriginKB = Int(sizeOrigin / 1024)
  if sizeOriginKB <= maxSize {
   return finallImageData!
  }
  //保存壓縮系數(shù)
  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)
  }
  //調(diào)整大小
  //說明:壓縮系數(shù)數(shù)組compressionQualityArr是從大到小存儲(chǔ)。
  //思路:折半計(jì)算,如果中間壓縮系數(shù)仍然降不到目標(biāo)值maxSize,則從后半部分開始尋找壓縮系數(shù);反之從前半部分尋找壓縮系數(shù)
  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("當(dāng)前降到的質(zhì)量:\(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("當(dāng)前降到的質(zhì)量:\(sizeOriginKB)")
    if sizeOriginKB > maxSize {
     print("\(idx)----\(value)")
     finallImageData = UIImageJPEGRepresentation(newImage, CGFloat(value as! NSNumber))
    } else {
     break
    }
   }
  }
  return finallImageData!
 }

Swift3.0版本二分法壓縮模式

// MARK: - 降低質(zhì)量
func resetSizeOfImageData(source_image: UIImage!, maxSize: Int) -> NSData {
 //先判斷當(dāng)前質(zhì)量是否滿足要求,不滿足再進(jìn)行壓縮
 var finallImageData = UIImageJPEGRepresentation(source_image,1.0)
 let sizeOrigin  = finallImageData?.count
 let sizeOriginKB = sizeOrigin! / 1024
 if sizeOriginKB <= maxSize {
  return finallImageData! as NSData
 }
 //先調(diào)整分辨率
 var defaultSize = CGSize(width: 1024, height: 1024)
 let newImage = self.newSizeImage(size: defaultSize, source_image: source_image)
 finallImageData = UIImageJPEGRepresentation(newImage,1.0);
 //保存壓縮系數(shù)
 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
 /*
  調(diào)整大小
  說明:壓縮系數(shù)數(shù)組compressionQualityArr是從大到小存儲(chǔ)。
  */
 //思路:使用二分法搜索
 finallImageData = self.halfFuntion(arr: compressionQualityArr.copy() as! [CGFloat], image: newImage, sourceData: finallImageData!, maxSize: maxSize)
 //如果還是未能壓縮到指定大小,則進(jìn)行降分辨率
 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: - 調(diào)整圖片分辨率/尺寸(等比例縮放)
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("當(dāng)前降到的質(zhì)量:\(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實(shí)現(xiàn)圖片壓縮的兩種方法,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的,在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • IOS開發(fā)代碼分享之獲取啟動(dòng)畫面圖片的string

    IOS開發(fā)代碼分享之獲取啟動(dòng)畫面圖片的string

    本文是IOS開發(fā)代碼分享系列的第一篇文章,這里分享下獲取啟動(dòng)畫面圖片的string的代碼,本代碼支持 iPhone 6 以下. 支持 iPhone 及 iPad,非常實(shí)用,希望對(duì)大家有所幫助
    2014-09-09
  • iOS實(shí)現(xiàn)類似格瓦拉電影的轉(zhuǎn)場(chǎng)動(dòng)畫

    iOS實(shí)現(xiàn)類似格瓦拉電影的轉(zhuǎn)場(chǎng)動(dòng)畫

    這篇文章主要給大家介紹了利用iOS如何實(shí)現(xiàn)類似格瓦拉電影的轉(zhuǎn)場(chǎng)動(dòng)畫,文中給出了詳細(xì)步驟實(shí)現(xiàn)代碼,對(duì)大家的學(xué)習(xí)和理解很有幫助,有需要的朋友們可以參考借鑒,下面來一起看看吧。
    2016-11-11
  • iOS延遲執(zhí)行方法詳解

    iOS延遲執(zhí)行方法詳解

    這篇文章主要為大家詳細(xì)介紹了iOS延遲執(zhí)行方法,包括performSelector(NSObject)方法、NSTimer、GCD和sleep(NSThread)四種方法,需要的朋友可以參考下
    2016-11-11
  • ios實(shí)現(xiàn)自動(dòng)獲取label高度、寬度及最后一個(gè)位置詳解

    ios實(shí)現(xiàn)自動(dòng)獲取label高度、寬度及最后一個(gè)位置詳解

    這篇文章主要給大家介紹了關(guān)于ios如何實(shí)現(xiàn)自動(dòng)獲取label高度、寬度及最后一個(gè)位置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • iOS自定義View實(shí)現(xiàn)卡片滑動(dòng)

    iOS自定義View實(shí)現(xiàn)卡片滑動(dòng)

    這篇文章主要為大家詳細(xì)介紹了ios自定義View實(shí)現(xiàn)卡片滑動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • ios原生二維碼掃描與生成的實(shí)現(xiàn)教程

    ios原生二維碼掃描與生成的實(shí)現(xiàn)教程

    這篇文章主要給大家介紹了關(guān)于ios原生二維碼掃描與生成的相關(guān)資料,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-09-09
  • iOS 獲取設(shè)備唯一標(biāo)示符的方法詳解

    iOS 獲取設(shè)備唯一標(biāo)示符的方法詳解

    本篇文章主要介紹了iOS 獲取設(shè)備唯一標(biāo)示符的方法詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08
  • iOS中給自定義tabBar的按鈕添加點(diǎn)擊放大縮小的動(dòng)畫效果

    iOS中給自定義tabBar的按鈕添加點(diǎn)擊放大縮小的動(dòng)畫效果

    這篇文章主要介紹了iOS中給自定義tabBar的按鈕添加點(diǎn)擊放大縮小的動(dòng)畫效果的相關(guān)資料,非常不錯(cuò),具有參考解決價(jià)值,需要的朋友可以參考下
    2016-11-11
  • iOS App中UIPickerView選擇欄控件的使用實(shí)例解析

    iOS App中UIPickerView選擇欄控件的使用實(shí)例解析

    這篇文章主要介紹了iOS App中的UIPickerView選擇欄控件的使用,文中演示了兩個(gè)超詳細(xì)的例子,示例代碼為Objective-C,需要的朋友可以參考下
    2016-04-04
  • iOS算法教程之分段截取常數(shù)示例

    iOS算法教程之分段截取常數(shù)示例

    這篇文章主要給大家介紹了關(guān)于iOS算法教程之分段截取常數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。
    2018-01-01

最新評(píng)論