首页 文章

在swift中从本地获取图像

提问于
浏览
1

我真的需要,真的很有帮助

我将Image保存到DocumentDirectory中如何拍摄此图像并放入UIImageView?

照片网址:

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

3 回答

  • 0

    尝试类似的东西:

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

    然后你可以把 image 放到 UIImageView .

    Other option (正如Leo Dabus在评论中提到的那样):

    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
    }
    
  • -1

    您可以使用NSFileManager的方法URLForDirectory来获取文档目录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)
    }
    
  • 3

    在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
    }
    

相关问题