gpt4 book ai didi

ios - 如何从文件目录保存和加载图像 - Swift 4

转载 作者:行者123 更新时间:2023-11-28 13:51:27 25 4
gpt4 key购买 nike

我正在尝试将图像保存到文件目录并从文件目录加载图像,但是我的 writeImageToPath 函数向控制台打印了以下错误,并指出该文件不存在。

控制台

Write image to directory

File exists Write image

Error Write image to directory File does NOT exist -- file:///Users/user/Library/Developer/CoreSimulator/Devices/70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6/data/Containers/Data/Application/DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09/Documents/upload/http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860 -- is available for use Write image Error Writing Image: Error Domain=NSCocoaErrorDomain Code=4 "The file “5202887448860” doesn’t exist." UserInfo={NSFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/70EAC77D-9F3C-4AFC-8CCA-A7B9B895BDE6/data/Containers/Data/Application/DDAF2EBD-5DDA-4EA6-95D3-6785B74A0B09/Documents/upload/http://i.annihil.us/u/prod/marvel/i/mg/a/f0/5202887448860, NSUnderlyingError=0x600003b04ab0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

这是我的代码,我不确定我哪里出错了

// The images are loaded from the web and displayed in the cell.imageView.image

if let thumbnail = product["thumbnail"] as? [String: Any],
let path = thumbnail["path"] as? String,
let fileExtension = thumbnail["extension"] as? String {

//Save image to directory
if image != nil {
writeImageToPath(path, image: image!)
}

}


// Write image to directory
func writeImageToPath(_ path: String, image: UIImage) {
print("Write image to directory")

let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

if !FileManager.default.fileExists(atPath: uploadURL.path) {
print("File does NOT exist -- \(uploadURL) -- is available for use")

let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

if let data = UIImageJPEGRepresentation(image, 0.9) {
do {
print("Write image")
try data.write(to: uploadURL)
}
catch {
print("Error Writing Image: \(error)")
}

} else {
print("Image is nil")
}
} else {
print("This file exists -- something is already placed at this location")
}

}


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


extension URL {
static func createFolder(folderName: String) -> URL? {
let fileManager = FileManager.default
// Get document directory for device, this should succeed
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
// Construct a URL with desired folder name
let folderURL = documentDirectory.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path) {
do {
// Attempt to create folder
try fileManager.createDirectory(atPath: folderURL.path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
// Creation failed. Print error & return nil
print(error.localizedDescription)
return nil
}
}
// Folder either exists, or was created. Return URL
return folderURL
}
// Will only be called if document directory not found
return nil
}
}

如何正确保存和加载目录中的图像?

最佳答案

class MyImageClass {
func writeImageToPath(_ path:String, image:UIImage) {
let uploadURL = URL.createFolder(folderName: "upload")!.appendingPathComponent(path)

if !FileManager.default.fileExists(atPath: uploadURL.path) {
print("File does NOT exist -- \(uploadURL) -- is available for use")
let data = image.jpegData(compressionQuality: 0.9)
do {
print("Write image")
try data!.write(to: uploadURL)
}
catch {
print("Error Writing Image: \(error)")
}
}
else {
print("This file exists -- something is already placed at this location")
}
}
}

extension URL {
static func createFolder(folderName: String) -> URL? {
let fileManager = FileManager.default
// Get document directory for device, this should succeed
if let documentDirectory = fileManager.urls(for: .documentDirectory,
in: .userDomainMask).first {
// Construct a URL with desired folder name
let folderURL = documentDirectory.appendingPathComponent(folderName)
// If folder URL does not exist, create it
if !fileManager.fileExists(atPath: folderURL.path) {
do {
// Attempt to create folder
try fileManager.createDirectory(atPath: folderURL.path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
// Creation failed. Print error & return nil
print(error.localizedDescription)
return nil
}
}
// Folder either exists, or was created. Return URL
return folderURL
}
// Will only be called if document directory not found
return nil
}
}

var saving = MyImageClass()
saving.writeImageToPath("whereIWantToSaveTheImageTo", image: UIImage(named: "myImage"))

引用资料 Create Directory in Swift 3.0

我没有测试成像是否有效,但是,这确实创建了一个名为“上传”的文件夹,您每次都可以调用它。该扩展有一个名为 createFolder 的方法,它会为您调用的任何内容返回一个文件夹,如果它不存在则创建它。我们可以只检查文件夹中的指定路径,然后如果它可用,我们就可以写入它。我也只重写了 writeImageToPath 部分。

注意:

在 Playground 上测试过这个......

结果是:

File does NOT exist -- file:///var/folders/vs/nlj__xh93vs0f8wzcgksh_zh0000gn/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-67A67A07-51FF-4DF4-BE80-02E7FDAFA1CA/Documents/upload/whereIWantToSaveTheImageTo -- is available for use
Write image

关于ios - 如何从文件目录保存和加载图像 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556820/

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