要將圖像保存到文檔目錄,您可以從創建保存圖像的函數開始,如下所示。該函數處理爲您創建圖像名稱並將其返回。
func saveImage(image: UIImage) -> String {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let uuid = NSUUID().uuidString + ".png"
let fullPath = docs.appendingPathComponent(uuid)
_ = imageData.write(toFile: fullPath, atomically: true)
return uuid
}
現在,因爲要保存圖像的數組,你可以簡單地循環,並調用saveImage功能:
for image in images {
saveImage(image: image)
}
如果您希望自己命名這些圖像,你可以修改的第一個函數以下幾點:
func saveImage(image: UIImage, withName name: String) {
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let docs = paths[0] as NSString
let name = name
let fullPath = docs.appendingPathComponent(name)
_ = imageData.write(toFile: fullPath, atomically: true)
}
當您將圖像保存爲UIImagePNGRepresentation你正在嘗試做的,請注意,是不保存的方向你。這意味着當您嘗試檢索圖像時,可能會標題爲左側。您需要重新繪製圖片以確保它的方向正確,因爲這篇文章將解釋how to save png correctly。但是,如果使用UIImageJPEGRepresentation保存圖像,則不必擔心所有這些,只需保存圖像即可,無需額外工作。
編輯以GIVE IMAGES
要獲取已保存的圖像,可以使用下面的函數,你傳遞圖像名稱的數組的數組,你會得到一個數組回來:
func getImage(imageNames: [String]) -> [UIImage] {
var savedImages: [UIImage] = [UIImage]()
for imageName in imageNames {
if let imagePath = getFilePath(fileName: imageName) {
savedImage.append(UIImage(contentsOfFile: imagePath))
}
}
return savedImages
}
依賴於該功能的工作:
func getFilePath(fileName: String) -> String? {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
var filePath: String?
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if paths.count > 0 {
let dirPath = paths[0] as NSString
filePath = dirPath.appendingPathComponent(fileName)
}
else {
filePath = nil
}
return filePath
}
讓一切:NSMutableArray的= arrayData作爲! NSMutableArray whatever.write(toFile:filename,atomically:true) –