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

编程入门 行业动态 更新时间:2024-10-22 12:30:32
本文介绍了如何使用 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))") } }

我没有收到任何错误,但图像没有保存在文档中.

I am not getting any error but the Image is not getting saved in the document.

推荐答案

问题是您正在检查文件夹是否不存在,但您应该检查文件是否存在.代码中的另一个问题是您需要使用 url.path 而不是 url.absoluteString.您还使用png"文件扩展名保存 jpeg 图像.你应该使用jpg".

The problem there is that you are checking if the folder not exists but you should check if the file exists. Another issue in your code is that you need to use url.path instead of url.absoluteString. You are also saving a jpeg image using a "png" file extension. You should use "jpg".

编辑/更新:

Swift 4.2 或更高版本

// get the documents directory url let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! // choose a name for your image let fileName = "image.jpg" // create the destination file url to save your image let fileURL = documentsDirectory.appendingPathComponent(fileName) // get your UIImage jpeg data representation and check if the destination file url already exists if let data = image.jpegData(compressionQuality: 1.0), !FileManager.default.fileExists(atPath: fileURL.path) { do { // writes the image data to disk try data.write(to: fileURL) print("file saved") } catch { print("error saving file:", error) } }

更多推荐

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

本文发布于:2023-10-04 09:10:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467141.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   图像   文档   目录中   writeToFile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!