ios - 使用存储文件的路径作为字符串存储和检索图像
问题描述
我正在使用 Realm 并将捕获图像的文件路径存储为String
s. 我想稍后检索它们以在 tableView 中使用。这是我存储每个图像的路径的代码:
func saveImage(imageName: String){
//create an instance of the FileManager
let fileManager = FileManager.default
//get the image path
thisImagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(imageName)
//get the image taken with camera
let image = originalCapturedImage
//get the PNG data for this image
let data = UIImagePNGRepresentation(image!)
//store it in the document directory
fileManager.createFile(atPath: thisImagePath as String, contents: data, attributes: nil)
print("Picture path at assignment \n")
print(thisImagePath as Any)
}
这是检索图像的代码:
...
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsPath = paths[0] //Get the docs directory
let filePath = URL(fileURLWithPath: documentsPath).appendingPathComponent(item.picPath).path
let image = UIImage(contentsOfFile: filePath)
print("Picture path at retrieval \n")
print(item.picPath as Any)
cell.imageWell.image = image
cell.imageWell.clipsToBounds = true
return cell
}
下面是运行时文件路径的对比:
Picture path at assignment
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
...
...
Picture path at retrieval
/var/mobile/Containers/Data/Application/0E9CACAD-C6B3-4F6C-B0DB-72C43AC722E1/Documents/1535219147
路径看起来与我相同,但没有出现图像。我已经搜索了整个 SO,并且有一次提到URL
了文件路径的使用。不知何故,我失去了那个条目的踪迹,再也找不到它了。
任何帮助将不胜感激!
解决方案
您可以尝试使用以下代码将图像写入文件,而不是创建包含内容的文件。 try? data.write(to: URL(fileURLWithPath: documentsPath))
您也可以参考下面的代码来保存图像。
class func saveImageToFileWithDirectory(_ imageData:Data, fileName:String, folderName : String? = nil) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentsDirectory = paths.object(at: 0) as! NSString
let path = documentsDirectory.appendingPathComponent(folderName) as NSString
if !FileManager.default.fileExists(atPath: path as String) {
do {
try FileManager.default.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
}
let imagePath = path.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: imagePath as String) {
try? imageData.write(to: URL(fileURLWithPath: imagePath))
} }
检索图像的代码看起来不错。如果您也需要帮助,请发表评论,我也会发布。
希望这可以解决您的问题。
推荐阅读
- azure - 如何在 Azure Key Vault 中添加键值?
- html - onClick - 将样式更改为多个 DOM 节点
- php - 当似乎没有语法错误时抛出 PHP 语法错误
- google-analytics - Google Analytics BigQuery 导出:获得不同的收入数字
- android - 目标 sdk 26 上的 Android Studio 应用程序在切换到目标 sdk 29 28 或其他情况时失去互联网
- javascript - 在 Bootstrap 4 中从单个模式加载多个 youtube 视频
- python - 我无法将线性方程符号化地求解为变量,即使手动完成它非常简单
- c# - C# OnClick .NET 框架坐标限制
- c# - 字符串未被识别为有效的日期时间。将字符串转换为日期时间
- java - 使用 Maven 执行器跳过模块