如何从本地路径 ios swift 加载图像(按路径)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37574689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:13:11  来源:igfitidea点击:

how to load image from local path ios swift (by path)

iosswiftimagensdocumentdirectory

提问by Hyman.Right

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)

And this is the path where my image stored

这是我的图像存储的路径

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)

回答by zsyesenko

Folder /B2A1EE50- ... changes every time you run application.

文件夹 /B2A1EE50- ... 每次运行应用程序时都会发生变化。

../Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/..

Which works for me is to store fileName and get documents folder.

对我有用的是存储文件名并获取文档文件夹。

Swift 3 +

斯威夫特 3 +

Create getter for directory folder

为目录文件夹创建 getter

var documentsUrl: URL {
    return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}

Save image :

保存图片 :

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
}

Load image :

加载图像:

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
}

回答by Jimmy James

Also you can try this.

你也可以试试这个。

  1. Check if your path exist
  1. 检查您的路径是否存在

if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {}

if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {}

  1. Create an URL to your path
  1. 为您的路径创建一个 URL

let url = NSURL(string: imageUrlPath)

let url = NSURL(string: imageUrlPath)

  1. Create data to you URL
  1. 为您的 URL 创建数据

let data = NSData(contentsOfURL: url!)

let data = NSData(contentsOfURL: url!)

  1. Bind the url to your imageView
  1. 将 url 绑定到您的 imageView

imageView.image = UIImage(data: data!)

imageView.image = UIImage(data: data!)

Final code:

最终代码

if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {
    let url = NSURL(string: imageUrlPath)
    let data = NSData(contentsOfURL: url!)
    imageView.image = UIImage(data: data!)
}

回答by Pankaj Jangid

This code works for me

这段代码对我有用

func getImageFromDir(_ imageName: String) -> UIImage? {

    if let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let fileURL = documentsUrl.appendingPathComponent(imageName)
        do {
            let imageData = try Data(contentsOf: fileURL)
            return UIImage(data: imageData)
        } catch {
            print("Not able to load image")
        }
    }
    return nil
}

回答by Konstantin Komarov

Swift 4:

斯威夫特 4:

if FileManager.default.fileExists(atPath: imageUrlPath) {
            let url = NSURL(string: imageUrlPath)
            let data = NSData(contentsOf: url! as URL)

            chapterImage.image = UIImage(data: data! as Data)
        }

回答by iYoung

Replace absoluteStringwith path

替换absoluteStringpath

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.path
        print(imageUrlPath)
        UIImageJPEGRepresentation(myimage,1.0)!.writeToFile(imageUrlPath, atomically: true)

回答by Fattie

This sample code may save someone some typing,

此示例代码可以节省一些人的输入,

write an UIImage to disk in your own directory:

将 UIImage 写入您自己目录中的磁盘:

IM = UIImage, your image. for example, IM = someUIView.image or from the camera

let newPhotoFileName = randomNameString() + ".jpeg"
let imagePath = checkedImageDirectoryStringPath() + "/" + newPhotoFileName

let imData = UIImageJPEGRepresentation(IM, 0.20)
FileManager.default.createFile(atPath: imagePath, contents: imData, attributes: nil)

print("saved at filename \(newPhotoFileName)")

later to read that image ...

稍后阅读该图像...

.. and convert it back to a UIImage as in a UIImageView

.. 并将其转换回 UIImage 就像在 UIImageView 中一样

NAME = that filename, like jahgfdfs.jpg

let p = checkedImageDirectoryStringPath() + "/" + NAME
devCheckExists(fullPath: p)

var imageData: Data? = nil
do {
    let u = URL(fileURLWithPath: p)
    imageData = try Data(contentsOf: u)
}
catch {
    print("catastrophe loading file?? \(error)")
    return
}

// and then to "make that an image again"...

imageData != nil {

    picture.image = UIImage(data: imageData!)
    print("that seemed to work")
}
else {

    print("the imageData is nil?")
}

// or for example...

Alamofire.upload(
    multipartFormData: { (multipartFormData) in
        multipartFormData.append(imageData!,
           withName: "file", fileName: "", mimeType: "image/jpeg")
    ...

Here are the extremely handy functions used above...

这是上面使用的非常方便的功能......

func checkedImageDirectoryStringPath()->String {

    // create/check OUR OWN IMAGE DIRECTORY for use of this app.

    let paths = NSSearchPathForDirectoriesInDomains(
                      .documentDirectory, .userDomainMask, true)

    if paths.count < 1 {
        print("some sort of disaster finding the our Image Directory - giving up")
        return "x"
        // any return will lead to disaster, so just do that
        // (it will then gracefully fail when you "try" to write etc)
    }

    let docDirPath: String = paths.first!
    let ourDirectoryPath = docDirPath.appending("/YourCompanyName")
    // so simply makes a directory called "YourCompanyName"
    // which will be there for all time, for your use

    var ocb: ObjCBool = true
    let exists = FileManager.default.fileExists(
                  atPath: ourDirectoryPath, isDirectory: &ocb)

    if !exists {
        do {
            try FileManager.default.createDirectory(
                    atPath: ourDirectoryPath,
                    withIntermediateDirectories: false,
                    attributes: nil)

            print("we did create our Image Directory, for the first time.")
            // never need to again
            return ourDirectoryPath
        }
        catch {
            print(error.localizedDescription)
            print("disaster trying to make our Image Directory?")
            return "x"
            // any return will lead to disaster, so just do that
        }
    }

    else {

        // already exists, as usual.
        return ourDirectoryPath
    }
}

and

func randomNameString(length: Int = 7)->String{

    enum s {
        static let c = Array("abcdefghjklmnpqrstuvwxyz12345789".characters)
        static let k = UInt32(c.count)
    }

    var result = [Character](repeating: "a", count: length)

    for i in 0..<length {
        let r = Int(arc4random_uniform(s.k))
        result[i] = s.c[r]
    }

    return String(result)
}

and

func devCheckExists(fullPath: String) {

    var ocb: ObjCBool = false
    let itExists = FileManager.default.fileExists(atPath: fullPath, isDirectory: &ocb)
    if !itExists {
        // alert developer. processes will fail at next step
        print("\n\nDOES NOT EXIST\n\(fullPath)\n\n")
    }
}

回答by RJ raj

1.cell.image.sd_setShowActivityIndicatorView(true)

1.cell.image.sd_setShowActivityIndi​​catorView(true)

2.cell.image.sd_setIndicatorStyle(.gray)

2.cell.image.sd_setIndicatorStyle(.gray)

3.cell.image.image = UIImage(contentsOfFile: urlString!)

3.cell.image.image = UIImage(contentsOfFile: urlString!)