【问题标题】:get Image from local in swift快速从本地获取图像
【发布时间】:2016-03-03 11:21:25
【问题描述】:

我真的需要帮助

我将图像保存到 DocumentDirectory 如何获取此图像并放入 UIImageView?

照片网址:

file:///Users/zoop/Library/Developer/CoreSimulator/Devices/3E9FA5C0-3III-41D3-A6D7-A25FF3424351/data/Containers/Data/Application/7C4D9316-5EB7-4A70-82DC-E76C654EA201/Documents/ profileImage.png

【问题讨论】:

    标签: swift uiimageview photo


    【解决方案1】:

    在 Swift 4.2 中:

    func getImageFromDirectory (_ imageName: String) -> UIImage? {
    
        if let fileURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(imageName).png") {
            // get the data from the resulting url
            var imageData : Data?
            do {
                 imageData = try Data(contentsOf: fileURL)
            } catch {
                print(error.localizedDescription)
                return nil
            }
            guard let dataOfImage = imageData else { return nil }
            guard let image = UIImage(data: dataOfImage) else { return nil }
            return image
        }
        return nil
    }
    

    【讨论】:

      【解决方案2】:

      试试这样的:

      let fileName = "profileImage.png"
      let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/" + fileName
      let image = UIImage(contentsOfFile: path)
      

      然后你可以把image 转成UIImageView

      其他选项(正如 Leo Dabus 在下面的 cmets 中提到的):

      let fileName = "profileImage.png"
      let fileURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!).URLByAppendingPathComponent(fileName)
      if let imageData = NSData(contentsOfURL: fileURL) {
          let image = UIImage(data: imageData) // Here you can attach image to UIImageView
      }
      

      【讨论】:

      • 它可能有效,但您不应该对文件路径进行硬编码
      • 是的,我知道,但在这里我展示了解决该问题的最简单方法。
      • 最简单的方法是使用 URLByAppendingPathComponent。顺便说一句,您应该开始习惯 NSURL 而不是常规字符串
      • 只需将文件名(路径组件)附加到文档目录url
      • 我正在使用URLByAppendingPathComponent
      【解决方案3】:

      可以使用 NSFileManager 的方法 URLsForDirectory 获取文档目录 url 和 URLByAppendingPathComponent 将文件名附加到原始 url:

      if let fileURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("profileImage.png"),
          // get the data from the resulting url
          let imageData = NSData(contentsOfURL: fileURL),
          // initialise your image object with the image data
          let image = UIImage(data: imageData) {
          print(image.size)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多