將圖片保存到沙盒下愉适,首先獲取沙盒路徑犯助,追加圖片名稱,將圖片轉(zhuǎn)換成NSData類(lèi)型维咸,寫(xiě)到文件里剂买。
persent參數(shù):圖片質(zhì)量參數(shù),該值越大癌蓖,表示圖片越清晰瞬哼,圖片文件也就越大
//保存圖片至沙盒
private func saveImage(currentImage: UIImage, persent: CGFloat, imageName: String){
if let imageData = UIImageJPEGRepresentation(currentImage, persent) as NSData? {
let fullPath = NSHomeDirectory().appending("/Documents/").appending(imageName)
imageData.write(toFile: fullPath, atomically: true)
print("fullPath=\(fullPath)")
}
}
也可以通過(guò)newSize自定義圖片的大小
private func saveImage(currentImage: UIImage, newSize: CGSize, imageName: String){
//壓縮圖片尺寸
UIGraphicsBeginImageContext(newSize)
currentImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
//UIImageJPEGRepresentation此方法可將圖片壓縮,但是圖片質(zhì)量基本不變租副,第二個(gè)參數(shù)即圖片質(zhì)量參數(shù)坐慰。
if let imageData = UIImageJPEGRepresentation(newImage, 1) as NSData? {
let fullPath = NSHomeDirectory().appending("/Documents/").appending(imageName)
imageData.write(toFile: fullPath, atomically: true)
print("fullPath=\(fullPath)")
}
}
}
從文件中讀取圖片
if let savedImage = UIImage(contentsOfFile: fullPath) {
self.imageView.image = savedImage
} else {
print("文件不存在")
}