OC 版本(任意大小压缩)
pragma mark - 修改图片大小,减小内存占用
-(UIImage *)scaleToSize:(CGSize)size {
//开启图片上下文
UIGraphicsBeginImageContext(size);
//渲染到上下文
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
//上下文获取图片
UIImage *endImage = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
return endImage;
}
Swift版本(指定宽度压缩)
// 压缩图片
/*
指定宽度来压缩
宽 1200 指定宽度 600
高 600 x
*/
func getImageScale(width: CGFloat) -> UIImage{
// 如果当前图片的宽度 小于程序员指定的宽度
if self.size.width < width {
return self
}
// 获取图片的最终高度
let height = (width*self.size.height)/self.size.width
// 设置rect
let rect = CGRect(x: 0, y: 0, width: width, height: height)
// 通过上下文
// 01 开启上下文
UIGraphicsBeginImageContext(rect.size)
// 02 将图片渲染到上下文中
self.drawInRect(rect)
// 03 从上下文获取image
let result = UIGraphicsGetImageFromCurrentImageContext()
// 04 关闭上下文
UIGraphicsEndImageContext()
return result
}