手机中经常会遇到一些非常大的图片,当把它们导入到我们的缓存时有时会造成程序的闪退,即超过了125mb,此时我们有三种方法对图片进行压缩,前两者方法http://blog.csdn.NET/mideveloper/article/details/11473627这位哥们讲的已经很详细了,我自己用OC和Swift写了一个UIImage的分类,也比较好用.
OC:
+(UIImage *)reduceScaleToWidth:(CGFloat)width andImage:(UIImage *)image{
if (image.size.width <= width) {
return image;
}
CGFloat height = image.size.height * (width/image.size.width);
CGRect rect = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage * returnImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return returnImage;
}
SWIFT
/// 将图片按指定宽度缩放
///
/// - parameter width: 指定宽度
///
/// - returns: <#return value description#>
func scaleToWidth(width: CGFloat) -> UIImage {
if size.width <= width {
return self
}
// 计算高度
let height = size.height * (width / size.width)
let rect = CGRect(x: 0, y: 0, width: width, height: height)
// 开启图形上下文
UIGraphicsBeginImageContext(rect.size)
// 画
self.drawInRect(rect)
// 取
let image = UIGraphicsGetImageFromCurrentImageContext()
// 关闭上下文
UIGraphicsEndImageContext()
return image
}