逛推酷的時候看了這哥們寫的《圖片壓縮邏輯》,感覺還不錯,于是自己用swift重寫了下,并進行了一點修改。
直接上代碼:
// Created by Bear on 2017/3/23.
// Copyright ? 2017年 BeargerHunter. All rights reserved.
//
import Foundation
import UIKit
extension UIImage{
/**
圖片壓縮的邏輯:
一:圖片尺寸壓縮 主要分為以下幾種情況 一般參照像素為targetPx
a.圖片寬高均≤targetPx時,圖片尺寸保持不變;
b.寬或高均>targetPx時 ——圖片寬高比≤2,則將圖片寬或者高取大的等比壓縮至targetPx; ——但是圖片寬高比>2時,則寬或者高取小的等比壓縮至targetPx;
c.寬高一個>targetPx,另一個<targetPx,--圖片寬高比>2時,則寬高尺寸不變;--但是圖片寬高比≤2時,則將圖片寬或者高取大的等比壓縮至targetPx.
二:圖片質(zhì)量壓縮: 對于超過大小閾值的圖片進行質(zhì)量壓縮,但不保證壓縮后的大小
一般圖片質(zhì)量都壓縮在90%就可以了
*/
open func confressImageView(targetPx:CGFloat, thresholdSize_KB:Int = 200)->Data?
{
var newImage:UIImage! // 尺寸壓縮后的新圖片
let imageSize:CGSize = self.size // 源圖片的size
let width:CGFloat = imageSize.width // 源圖片的寬
let height:CGFloat = imageSize.height // 原圖片的高
var drawImge:Bool = false // 是否需要重繪圖片 默認是NO
var scaleFactor:CGFloat = 0.0 // 壓縮比例
var scaledWidth:CGFloat = targetPx // 壓縮時的寬度 默認是參照像素
var scaledHeight:CGFloat = targetPx // 壓縮是的高度 默認是參照像素
if width <= targetPx,height <= targetPx {
newImage = self
}
else if width >= targetPx , height >= targetPx {
drawImge = true
let factor:CGFloat = width / height
if factor <= 2 {
// b.1圖片寬高比≤2,則將圖片寬或者高取大的等比壓縮至targetPx
scaleFactor = width > height ? targetPx/width : targetPx/height
} else {
// b.2圖片寬高比>2時,則寬或者高取小的等比壓縮至targetPx
scaleFactor = width > height ? targetPx/height : targetPx/width
}
}
// c.寬高一個>targetPx,另一個<targetPx 寬大于targetPx
else if width >= targetPx , height <= targetPx {
if width / height > 2 {
newImage = self;
} else {
drawImge = true;
scaleFactor = targetPx / width;
}
}
// c.寬高一個>targetPx,另一個<targetPx 高大于targetPx
else if width <= targetPx , height >= targetPx {
if height / width > 2 {
newImage = self;
} else {
drawImge = true;
scaleFactor = targetPx / height;
}
}
// 如果圖片需要重繪 就按照新的寬高壓縮重繪圖片
if drawImge {
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
UIGraphicsBeginImageContext(CGSize(width:scaledWidth,height:scaledHeight));
// 繪制改變大小的圖片
self.draw(in: CGRect.init(x: 0, y: 0, width: scaledWidth, height: scaledHeight))
// 從當前context中創(chuàng)建一個改變大小后的圖片
newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當前的context出堆棧
UIGraphicsEndImageContext();
}
// 如果圖片大小大于200kb 在進行質(zhì)量上壓縮
var scaledImageData:Data? = nil;
guard newImage != nil else {
return nil;
}
if (UIImageJPEGRepresentation(newImage!, 1) == nil) {
scaledImageData = UIImagePNGRepresentation(newImage);
}else{
scaledImageData = UIImageJPEGRepresentation(newImage, 1);
guard scaledImageData != nil else {
return nil
}
if scaledImageData!.count >= 1024 * thresholdSize_KB {
scaledImageData = UIImageJPEGRepresentation(newImage, 0.9);
}
}
return scaledImageData
}
}