我正在使用saveImage保存图像.
func saveImage (image: UIImage,path: String ) -> Bool{ let pngImageData = UIImagePNGRepresentation(image) //let jpgImageData = UIImageJPEGRepresentation(image,1.0) // if you want to save as JPEG print("!!!saving image at: \(path)") let result = pngImageData!.writeToFile(path,atomically: true) return result }
新信息:
保存文件无法正常工作(打印“[ – ] ERROR SAVING FILE”) –
// save your image here into Document Directory let res = saveImage(tempImage,path: fileInDocumentsDirectory("abc.png")) if(res == true){ print ("[+] FILE SAVED") }else{ print ("[-] ERROR SAVING FILE") }
为什么saveImage函数没有保存图像?访问权?
旧信息:
调试信息说:
!!!saving image at: file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/Documents/tempImage
然后我使用检索此位置
fileInDocumentsDirectory("tempImage")
结果是正确的.
然后我使用此路径加载文件
let image = UIImage(contentsOfFile: path) if image == nil { print("missing image at: \(path)") }else{ print("!!!IMAGE FOUND at: \(path)") }
路径是正确的,但消息是“在…处丢失图像”.文件是否以某种方式无法访问或未存储?这种行为可能是什么原因?
我正在使用ios 7和带有ios 7模拟器的iphone 5在iphone 4上测试此代码.
编辑:
1. fileInDocumentsDirectory函数
func fileInDocumentsDirectory(filename: String) -> String { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask)[0] let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString return fileURL }
斯威夫特3
func saveImage(image: UIImage) -> Bool { guard let data = UIImageJPEGRepresentation(image,1) ?? UIImagePNGRepresentation(image) else { return false } guard let directory = try? FileManager.default.url(for: .documentDirectory,in: .userDomainMask,appropriateFor: nil,create: false) as NSURL else { return false } do { try data.write(to: directory.appendingPathComponent("fileName.png")!) return true } catch { print(error.localizedDescription) return false } }
使用:
let success = saveImage(image: UIImage(named: "image.png")!)
这个函数将获得该图像:
func getSavedImage(named: String) -> UIImage? { if let dir = try? FileManager.default.url(for: .documentDirectory,create: false) { return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path) } return nil }
使用:
if let image = getSavedImage(named: "fileName") { // do something with image }