Swift 图片压缩

2018-02-27 11:28:00来源:oschina作者:SimonXun人点击

分享

func compressionImage(image: UIImage, compressionQuality: CGFloat) -> Data? {


//实现等比例缩放
let hfactor = image.size.width / screenWidth;
let vfactor = image.size.height / screenHeight;
let factor = fmax(hfactor, vfactor);
//画布大小
let newWith: CGFloat = image.size.width / factor
let newHeigth: CGFloat = image.size.height / factor
let newSize = CGSize(width: newWith, height: newHeigth)UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
image.draw(in: CGRect(x: 0, y: 0, width: newWith, height: newHeigth))let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()if let compressionImage = newImage {
//图像压缩
let newImageData = UIImageJPEGRepresentation(compressionImage, compressionQuality)
if let data = newImageData {
return data
}
}return nil
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台