如何使用writeToFile将图像保存在文档目录中?

// directoryPath is a URL from another VC @IBAction func saveButtonTapped(sender: AnyObject) { let directoryPath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let urlString : NSURL = directoryPath.URLByAppendingPathComponent("Image1.png") print("Image path : \(urlString)") if !NSFileManager.defaultManager().fileExistsAtPath(directoryPath.absoluteString) { UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.absoluteString, atomically: true) displayImageAdded.text = "Image Added Successfully" } else { displayImageAdded.text = "Image Not Added" print("image \(image))") } } 

我没有得到任何错误,但图像没有被保存在文档中。

问题是你正在检查文件夹是否存在,你应该检查文件是否存在。 你也应该使用url.path! 而不是url.absoluteString。 您还使用png文件扩展名保存您的JPEG图像。 你应该使用.jpg。

 let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) // create a name for your image let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("Image1.jpg") if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) { if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) { print("file saved") } else { print("error saving file") } } else { print("file already exists") } 

这是我对Swift 3的回答,结合上面的2个答案:

 let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // create a name for your image let fileURL = documentsDirectoryURL.appendingPathComponent("Savedframe.png") if !FileManager.default.fileExists(atPath: fileURL.path) { do { try UIImagePNGRepresentation(imageView.image!)!.write(to: fileURL) print("Image Added Successfully") } catch { print(error) } } else { print("Image Not Added") } 
 @IBAction func saveButtonTapped(sender: AnyObject) { let directoryPath = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) let urlString : NSURL = directoryPath.URLByAppendingPathComponent("Image1.png") print("Image path : \(urlString)") if !NSFileManager.defaultManager().fileExistsAtPath(urlString.path!) { UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.path! , atomically: true) displayImageAdded.text = "Image Added Successfully" } else { displayImageAdded.text = "Image Not Added" print("image \(image))") } } 

把图像放在一个NSData对象中; 用这个类写入文件是一件轻而易举的事情,它会使文件变小。

顺便说一下,我推荐NSPurgeableData。 保存图像后,可以将对象标记为可清除,这将保持内存消耗。 这可能是你的应用程序的问题,但可能与另一个你挤出。

Interesting Posts