【问题标题】:how to use writeToFile to save image in document directory?如何使用 writeToFile 将图像保存在文档目录中?
【发布时间】:2015-12-26 12:20:04
【问题描述】:
// 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))")
            }
        }

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

【问题讨论】:

  • 这段代码有什么问题?
  • 我没有收到任何错误,但图像没有保存在文档中。
  • @ if !NSFileManager.defaultManager().fileExistsAtPath(urlString.path!) {
  • 您正在检查文件夹是否不存在,您应该检查文件 url
  • ty 这么多,你节省了我的时间,代码现在可以工作了!!我刚刚将 .absoluteString 替换为 .path!它工作得很好@LeoDabus。

标签: ios swift xcode image writetofile


【解决方案1】:

问题是您正在检查文件夹是否不存在,但您应该检查文件是否存在。您的代码中的另一个问题是您需要使用 url.path 而不是 url.absoluteString。您还使用“png”文件扩展名保存 jpeg 图像。你应该使用“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)
    }
}

【讨论】:

  • 注意:也可以使用writeToURL代替.path!
  • 如果您在答案中解释问题所在,而不是仅仅发布代码,将会更有帮助。不能指望未来的读者会浏览所有问题的 cmets,甚至有时会删除 cmets。
  • @MartinR 好的,我会添加信息
  • @LeoDabus : 如何为下载的图片设置名称?
  • @JayprakashDubey 如果您使用的是URLSession,您可以使用suggestedFilenamesuggestedFilename 属性URLResponsedeveloper.apple.com/documentation/foundation/urlresponse/…
【解决方案2】:

这是我对 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")
}

【讨论】:

  • 图片保存在哪里?由于我使用了此代码并且打印了“图像添加成功”日志,但无法在照片中找到图像..
【解决方案3】:

swift 4.2中的扩展方法

import Foundation
import UIKit

extension UIImage {

    func saveToDocuments(filename:String) {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsDirectory.appendingPathComponent(filename)
        if let data = self.jpegData(compressionQuality: 1.0) {
            do {
                try data.write(to: fileURL)
            } catch {
                print("error saving file to documents:", error)
            }
        }
    }

}

【讨论】:

    【解决方案4】:
    @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))")
        }
    }
    

    【讨论】:

    • 应该更好地命名你的 vars directoryPath 它不是路径。这是一个网址
    • urlString 它不是一个字符串。看看我选择的命名
    • 我知道它不是一个字符串,而是代码“UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(fileURL, atomically: true)” 它给出的错误不能将nsurl转换成字符串所以有放.path!
    • 您只需将 writeToFile 更改为 writeToURL
    • @Niched Arora 您还使用 png 文件扩展名保存 jpeg 图像。您应该使用 .jpg。或 UIImagePNGRepresentation
    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

      在 Swift 4.2 和 Xcode 10.1 中

      func saveImageInDocsDir() {
      
          let image: UIImage? = yourImage//Here set your image
          if !(image == nil) {
              // get the documents directory url
              let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
              let documentsDirectory = paths[0] // Get documents folder
              let dataPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("ImagesFolder").absoluteString //Set folder name
              print(dataPath)
              //Check is folder available or not, if not create 
              if !FileManager.default.fileExists(atPath: dataPath) {
                  try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: true, attributes: nil) //Create folder if not
              }
      
              // create the destination file url to save your image
              let fileURL = URL(fileURLWithPath:dataPath).appendingPathComponent("imageName.jpg")//Your image name
              print(fileURL)
              // get your UIImage jpeg data representation
              let data = UIImageJPEGRepresentation(image!, 1.0)//Set image quality here
              do {
                  // writes the image data to disk
                  try data?.write(to: fileURL, options: .atomic)
              } catch {
                  print("error:", error)
              }
          }
      }
      

      【讨论】:

      • 分享如何从磁盘检索图像也会很有用。
      【解决方案7】:

      Swift 5.x 的答案

      func saveImageToDocumentsDirectory() {
              let directoryPath =  try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
              let urlString : NSURL = directoryPath.appendingPathComponent("Image1.png") as NSURL
                  print("Image path : \(urlString)")
              if !FileManager.default.fileExists(atPath: urlString.path!) {
                  do {
                      try self.image.jpegData(compressionQuality: 1.0)!.write(to: urlString as URL)
                      print ("Image Added Successfully")
                  } catch {
                      print ("Image Not added")
                  }
              }
          }
      

      注意:图片 = 您声明的图片。

      【讨论】:

        【解决方案8】:

        虽然答案是正确的,但我想为此分享实用功能。您可以使用以下 2 种方法将图像保存在 Documents Directory 中,然后从 Documents Directory 加载图像。在这里你可以找到Detailed Article

        public static func saveImageInDocumentDirectory(image: UIImage, fileName: String) -> URL? {
        
                let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
                let fileURL = documentsUrl.appendingPathComponent(fileName)
                if let imageData = UIImagePNGRepresentation(image) {
                    try? imageData.write(to: fileURL, options: .atomic)
                    return fileURL
                }
                return nil
            }
        
        public static func loadImageFromDocumentDirectory(fileName: String) -> UIImage? {
        
                let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
                let fileURL = documentsUrl.appendingPathComponent(fileName)
                do {
                    let imageData = try Data(contentsOf: fileURL)
                    return UIImage(data: imageData)
                } catch {}
                return nil
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-05
          • 1970-01-01
          • 2016-06-24
          • 2018-10-13
          • 1970-01-01
          • 2022-01-04
          相关资源
          最近更新 更多