从swift文件目录中获取图像
说我正在使用这个代码来保存图像到文件directroy
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent("Image.png") let image = UIImage(named: readPath) let writePath = dirPath.stringByAppendingPathComponent("Image2.png") UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true) } } }
我将如何回顾它? 请记住,在iOS8中,确切的path经常变化
您在运行时查找文档目录path来编写图像,为了读取它,您可以使用确切的逻辑:
Swift 3
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) if let dirPath = paths.first { let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png") let image = UIImage(contentsOfFile: imageURL.path) // Do whatever you want with the image }
Swift 2
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent("Image2.png") let image = UIImage(contentsOfFile: readPath) // Do whatever you want with the image } } }
Swift 2
如果你想从Swift 2的文档目录中获取文件:
let path: String? = NSBundle.mainBundle().pathForResource("imageName", ofType: "png", inDirectory: "DirectoryName/Images") let imageFromPath = UIImage(contentsOfFile: path!)! self.myImage.image = imageFromPath
希望能帮助别人
作为延伸更好。
extension URL { static var documentsDirectory: URL { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return try! documentsDirectory.asURL() } static func urlInDocumentsDirectory(with filename: String) -> URL { return documentsDirectory.appendingPathComponent(filename) } }
像这样使用:
let path = URL.urlInDocumentsDirectory(with: filename).path let image = UIImage(contentsOfFile: path)