UIImage+Extension.swift
//
// UIImage+Extension.swift
// 逗牛
//
// Created by mac on 16/3/7.
// Copyright ? 2016年 mac. All rights reserved.
//
import UIKit
extension UIImage {
///對(duì)指定圖片進(jìn)行拉伸
func resizableImage(name: String) -> UIImage {
var normal = UIImage(named: name)!
let imageWidth = normal.size.width * 0.5
let imageHeight = normal.size.height * 0.5
normal = resizableImageWithCapInsets(UIEdgeInsetsMake(imageHeight, imageWidth, imageHeight, imageWidth))
return normal
}
/**
* 壓縮上傳圖片到指定字節(jié)
*
* image 壓縮的圖片
* maxLength 壓縮后最大字節(jié)大小
*
* return 壓縮后圖片的二進(jìn)制
*/
func compressImage(image: UIImage, maxLength: Int) -> NSData? {
let newSize = self.scaleImage(image, imageLength: 300)
let newImage = self.resizeImage(image, newSize: newSize)
var compress:CGFloat = 0.9
var data = UIImageJPEGRepresentation(newImage, compress)
while data?.length > maxLength && compress > 0.01 {
compress -= 0.02
data = UIImageJPEGRepresentation(newImage, compress)
}
return data
}
/**
* 通過指定圖片最長(zhǎng)邊,獲得等比例的圖片size
*
* image 原始圖片
* imageLength 圖片允許的最長(zhǎng)寬度(高度)
*
* return 獲得等比例的size
*/
func scaleImage(image: UIImage, imageLength: CGFloat) -> CGSize {
var newWidth:CGFloat = 0.0
var newHeight:CGFloat = 0.0
let width = image.size.width
let height = image.size.height
if (width > imageLength || height > imageLength){
if (width > height) {
newWidth = imageLength;
newHeight = newWidth * height / width;
}else if(height > width){
newHeight = imageLength;
newWidth = newHeight * width / height;
}else{
newWidth = imageLength;
newHeight = imageLength;
}
}
return CGSize(width: newWidth, height: newHeight)
}
/**
* 獲得指定size的圖片
*
* image 原始圖片
* newSize 指定的size
*
* return 調(diào)整后的圖片
*/
func resizeImage(image: UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.drawInRect(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。