在swift中从本地获取图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在swift中从本地获取图像相关的知识,希望对你有一定的参考价值。

我真的非常需要帮助

我将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

答案

尝试类似的东西:

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

然后你可以把image放到UIImageView

其他选择(正如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
}
另一答案

您可以使用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)
}
另一答案

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

以上是关于在swift中从本地获取图像的主要内容,如果未能解决你的问题,请参考以下文章

在 iOS Swift 中从设备获取图像的 URL 路径

如何在swift3中从库的PHAsset中获取图像文件名

如何在swift中从UIImage获取图像扩展/格式

在 Swift 中从 HTML 生成带有图像的 PDF 而不显示打印界面

如何在片段中从相机捕获图像,

在 Swift 中从相机中裁剪图像而不移动到另一个 ViewController