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

后端 未结 8 1630
长情又很酷
长情又很酷 2020-12-04 20:02

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 a

相关标签:
8条回答
  • 2020-12-04 20:54

    This is working for me and I think is a fast and clean way to do it.

    Swift 5.0

    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)
    let imageData = try? Data(contentsOf: imageUrl)
    let image = UIImage(data: imageData!)
    

    Where "imageUrl" is the value of your imageURL from documents folder. And "image" is the resulting image you can use anywhere you need.

    0 讨论(0)
  • 2020-12-04 20:56

    This sample code may save someone some typing,

    write an UIImage to disk in your own directory:

    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

    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")
        }
    }
    
    0 讨论(0)
提交回复
热议问题