在做发送图片的时候发现,iOS发送给安卓的base64文件时,安卓解压读取会崩溃,原因说是由于图片过大.下面是一种压缩图片又避免失真特严重的方法
//压缩图片
extension UIImage {
func resizeImage(image: UIImage, newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
var newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let data:NSData = UIImageJPEGRepresentation(newImage!, 1)! as NSData
print(data.length / 1000)
if data.length / 1000 > 150 {
let size = CGSize.init(width: (newImage?.size.width)! / 5, height: (newImage?.size.height)! / 5)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
let dataNew:NSData = UIImageJPEGRepresentation(newImage!, 1)! as NSData
print(dataNew.length / 1000)
if dataNew.length / 1000 > 150 {
let size = CGSize.init(width: (newImage?.size.width)! / 5, height: (newImage?.size.height)! / 5)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
return newImage!
}
}