[英]How can I save a photo taken with UIImagePickerController camera to be displayed later in the app?
我讓用戶使用UIImagePickerController拍攝照片,我需要將其保存到應用程序中,以便在以后需要查看時可以顯示它。 我該怎么做?
我聽說NSUserDefaults將是一個錯誤。 我需要保存的只是一張圖像,再也沒有。
這是將圖像保存到文檔文件夾的功能
func saveImage (image: UIImage, path: String ) -> Bool{
let pngImageData = UIImagePNGRepresentation(image)
//let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // if you want to save as JPEG
let result = pngImageData.writeToFile(path, atomically: true)
return result
}
這是獲取帶有圖像名稱的文檔目錄路徑的功能
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
return documentsFolderPath.stringByAppendingPathComponent(filename)
}
這是一個如何使用圖像路徑的示例
let imagePath = fileInDocumentsDirectory(myImageName)
這是將圖像保存到該文件夾的方法
saveImage(image, path: imagePath)
現在最后一部分是獲取圖像,因此請使用此功能獲取圖像
func loadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: path)
if image == nil {
println("Image not available at: (path)")
}
return image
}
這是您使用上述功能的方式
image = loadImageFromPath(imagePath)
imageView.image = image
希望這對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.