gpt4 book ai didi

arrays - 尝试从 DocumentDirectory 路径获取图像时出错

转载 作者:行者123 更新时间:2023-11-30 13:06:09 24 4
gpt4 key购买 nike

我正在尝试在 DocumentDirectory 路径中存储图像数组
这是我存储图像的代码

 let img = photo //Change to be from UIPicker
let data = UIImagePNGRepresentation(img!)!
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
try data.writeToFile("\(documentsPath)(myImage)", options: [])

} catch {
print("Error")
}

这就是我获取图像的方式

  override func viewDidLoad() {
super.viewDidLoad()

do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let readData = try NSData(contentsOfFile: "\(documentsPath)(myImage)", options: [])
let retreivedImage = UIImage(data: readData)
image = retreivedImage
photos.append(image!)

}

catch {
print("Error")
}

我的问题是,当我保存第一个图像时,我可以加载它,但是当我添加多于 1 个图像并保存它时,我无法重新加载它

最佳答案

我想这会对你有帮助。这段代码对我有用。

您可以使用 swift3.0 下载图像并将其保存到文档目录,如下所示

/// Get Document directory path

var 目录路径:字符串{

    let baseUrl = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

print("Base Url: \(baseUrl.first!)")

return baseUrl.first!
}

///添加图片到Document目录

func addImage(_ image: UIImage, name: String) -> Bool {

    var path = directoryPath

path.append("/\(name)")

return FileManager.default.createFile(atPath: path, contents: UIImageJPEGRepresentation(image, 1.0), attributes: nil)
}

/// fetch a image from document directory

func fetchImage(name: String) -> UIImage? {

    var imagePath = directoryPath

imagePath.append("/\(name)")

if FileManager.default.fileExists(atPath: imagePath) {

return UIImage(contentsOfFile: imagePath)!

} else {

return nil

}
}

关于arrays - 尝试从 DocumentDirectory 路径获取图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com