如何从本地路径加载图像ios swift(按路径) [英] how to load image from local path ios swift (by path)
本文介绍了如何从本地路径加载图像ios swift(按路径)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我将图像存储在本地存储中,并且我在数据库中保存该图像的路径。如何从该路径加载图片?
In my app I am storing an image in local storage and I am saving the path of that image in my database. How can I load the image from that path?
以下是我用来保存图片的代码:
Here is the code I am using in order to save the image:
let myimage : UIImage = UIImage(data: data)!
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = urls[0] as NSURL
print(documentDirectory)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .NoStyle
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let convertedDate = dateFormatter.stringFromDate(currentDate)
let imageURL = documentDirectory.URLByAppendingPathComponent(convertedDate)
imageUrlPath = imageURL.absoluteString
print(imageUrlPath)
UIImageJPEGRepresentation(myimage,1.0)!.writeToFile(imageUrlPath, atomically: true)
这是我存储图像的路径
file:///var/mobile/Containers/Data/Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/2016-06-01%2021:49:32
这是我试图检索图像的方式,但它没有显示任何内容。
This is how i tried to retrieve the image but it's not displaying anything.
let image : String = person?.valueForKey("image_local_path") as! String
print(person!.valueForKey("image_local_path")! as! String)
cell.img_message_music.image = UIImage(contentsOfFile: image)
推荐答案
文件夹/ B2A1EE50- ...每次运行应用程序时都会更改。
Folder /B2A1EE50- ... changes every time you run application.
../Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/..
对我有用的是存储fileName和获取文档文件夹。
Which works for me is to store fileName and get documents folder.
Swift 3 +
为目录文件夹创建getter
Create getter for directory folder
var documentsUrl: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
保存图片:
private func save(image: UIImage) -> String? {
let fileName = "FileName"
let fileURL = documentsUrl.appendingPathComponent(fileName)
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
try? imageData.write(to: fileURL, options: .atomic)
return fileName // ----> Save fileName
}
print("Error saving image")
return nil
}
加载图片:
private func load(fileName: String) -> UIImage? {
let fileURL = documentsUrl.appendingPathComponent(fileName)
do {
let imageData = try Data(contentsOf: fileURL)
return UIImage(data: imageData)
} catch {
print("Error loading image : \(error)")
}
return nil
}
这篇关于如何从本地路径加载图像ios swift(按路径)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文