将图像保存到文件目录
Posted
技术标签:
【中文标题】将图像保存到文件目录【英文标题】:Save image to the File Directory 【发布时间】:2019-02-06 02:36:26 【问题描述】:我正在尝试使用文件目录保存图像,但我无法在没有错误提示的情况下保存图像
没有这样的文件夹。
这是我的代码,我不知道哪里出错了
// Write image to directory
func writeImageToPath(_ path: String, image: UIImage)
print("Write image to directory")
// get the documents directory url
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let folderURL = documentsURL.appendingPathComponent("upload")
if !FileManager.default.fileExists(atPath: folderURL.path)
do
try FileManager.default.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
catch
let fileURL = folderURL.appendingPathComponent(path)
let data = UIImageJPEGRepresentation(image, 0.9)
do
try data!.write(to: fileURL)
catch
// load image from directory
func loadImageFromPath(_ path: String) -> UIImage?
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let folderURL = documentsURL.appendingPathComponent("upload")
let fileURL = folderURL.appendingPathComponent(path)
if FileManager.default.fileExists(atPath: fileURL.path)
//Get Image And upload in server
print("fileURL.path \(fileURL.path)")
do
let data = try Data.init(contentsOf: fileURL)
let image = UIImage(data: data)
return image
catch
print("error getting image")
else
print("No image in directory")
return nil
如何正确保存和加载目录中的图像?
【问题讨论】:
我不想提供答案,而是想告诉您您所犯的错误。首先,您必须在编写imageData
之前创建目录。其次,您需要使用扩展名.jpg, .png
作为完整路径中的图像名称。
【参考方案1】:
罗,
在大多数项目中,我一直在遵循以下 sn-p 代码:
要将图像保存在文件夹中,请使用以下函数:
func addImageInFolder(image : UIImage,filename:String)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let folderURL = documentsURL.appendingPathComponent("upload")
if !FileManager.default.fileExists(atPath: folderURL.path)
do
try FileManager.default.createDirectory(atPath: folderURL.path, withIntermediateDirectories: true, attributes: nil)
catch
let fileURL = folderURL.appendingPathComponent(filename)
let data = UIImageJPEGRepresentation(image, 0.9)
do
try data!.write(to: fileURL)
catch
使用以下功能从存储的文件夹中删除图像:
let fileURL = documentsURL.appendingPathComponent("upload/\(filename ?? "")")
if FileManager.default.fileExists(atPath: fileURL.absoluteString)
do
try FileManager.default.removeItem(at: fileURL)
catch
print("\(sigStr ?? "") delete file delete error")
从文件夹中获取图片:
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//TODO: -Get dateTime For get image URL-
let fileURL = documentsURL.appendingPathComponent("upload/\(fileName)")
if FileManager.default.fileExists(atPath: fileURL.path)
//Get Image And upload in server
print("fileURL.path \(fileURL.path)")
do
let data = try Data.init(contentsOf: fileURL)
imageView.image = UIImage(data: data)
catch
【讨论】:
您好,谢谢您的回答。保存图像时我不再收到任何错误,但是在加载时我没有得到任何结果。我已经用我的加载功能更新了我的问题,我怎样才能加载图像并返回它?感谢您的帮助 @A.Roe 我已经更新了我的答案。希望它能解决你的问题。 谢谢,但由于某种原因,在检索图像时找不到文件,我更新了问题中的代码,您可以看到控制台打印的位置 print("No image in directory" ),有什么想法吗?【参考方案2】:Swift 4.2
func saveAndGetImageFromDirectory(_ data: Data, name: String, completionHandler: @escaping (URL?)->())
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var imageURL:URL!
imageURL = documentsURL.appendingPathComponent(name)
do
try data.write(to: imageURL)
var documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
documentsPath = documentsPath + "/\(name)"
completionHandler(URL.init(fileURLWithPath: documentsPath))
catch let error
print(error)
【讨论】:
NSSearchPathForDirectoriesInDomains
已过时且 objective-c-ish。并且永远不要使用+
和连接字符串构建路径【参考方案3】:
Swift 4:
try this code maybe it will helps you.
//saving image in directory and
let fileManager = FileManager.default
//get the image path
let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
//get the image we took from gallery
let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
//get the PNG data for this image
let data = image!.pngData()
//store it in the document directory
fileManager.createFile(atPath: imagePath as String, contents: data, attributes: nil)
【讨论】:
不要使用(NS)String
构建路径。 NSSearchPathForDirectoriesInDomains
已过时。使用 FileManager 的 URL 相关 API,appendingPathComponent()
等方法已移至URL
。以上是关于将图像保存到文件目录的主要内容,如果未能解决你的问题,请参考以下文章