在swift中从本地获取图像

问题描述 投票:2回答:3

我真的非常需要帮助

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

swift uiimageview photo
3个回答
4
投票

尝试类似的东西:

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
}

0
投票

您可以使用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)
}

-1
投票

在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
}
© www.soinside.com 2019 - 2024. All rights reserved.