2018-06-27
Swift 图片转换 压缩
PNG图片转UIImage
let image = UIImage(named :"PNG图片名.png")
UIImage转Data
let data = UIImagePNGRepresentation( image )
Data转UIImage
let image = UIImage(data : data)
//多张照片上传时 经常出现内存警告的问题, (当第二次警告时app就会闪退)
这事犹豫iOS 默认只给了20M的内存。所以就需要对图片进行压缩
/**
* 图片压缩
*/
funczipImage(currentImage:UIImage,scaleSize:CGFloat,percent:CGFloat) ->NSData{
//压缩图片尺寸
UIGraphicsBeginImageContext(CGSize(width: currentImage.size.width*scaleSize, height: currentImage.size.height*scaleSize))
currentImage.draw(in:CGRect(x:0, y:0, width: currentImage.size.width*scaleSize, height:currentImage.size.height*scaleSize))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
//高保真压缩图片质量
//UIImageJPEGRepresentation此方法可将图片压缩,但是图片质量基本不变,第二个参数即图片质量参数。
letimageData:NSData=UIImageJPEGRepresentation(newImage, percent)!asNSData
returnimageData
}
//图片压缩的相关记录
UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数而UIImagePNGRepresentation只需要图片引用作为参数.
UIImagePNGRepresentation(UIImage *image)要比UIImageJPEGRepresentation(UIImage* image, 1.0)返回的图片数据量大很多.