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

时间:2016-06-01 16:57:59

标签: ios swift image nsdocumentdirectory

在我的应用程序中,我将图像存储在本地存储中,并且我在数据库中保存该图像的路径。如何从该路径加载图像?

以下是我用来保存图片的代码:

read_file(Stream, Lines) :-
    read(Stream, Line),               % Attempt a read Line from the stream
    (  at_end_of_stream(Stream)       % If we're at the end of the stream then...
    -> Lines = []                     % ...lines read is empty
    ;  Lines = [Line|NewLines],       % Otherwise, Lines is Line followed by
       read_file(Stream, NewLines)    %   a read of the rest of the file
    ).

这是我存储图像的路径

?- open('test.txt', read, Str), read_file(Str, Lines), close(Str), write(Lines), nl.
Str = <stream>(0x871c410),
Lines = [birthbook(tom, 9, 1), birthbook(add, 9, 1), birthbook(ddd, 8, 1)].

?-

这是我试图检索图像的方式,但它没有显示任何内容。

 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)

8 个答案:

答案 0 :(得分:34)

Folder / B2A1EE50- ...每次运行应用程序时都会更改。

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

对我来说有用的是存储fileName和获取文档文件夹。

Swift 3 +

为目录文件夹

创建getter
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
}

答案 1 :(得分:9)

你也可以试试这个。

  1. 检查您的路径是否存在
  2. if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {}

    1. 创建路径的网址
    2. let url = NSURL(string: imageUrlPath)

      1. 为您创建数据网址
      2. let data = NSData(contentsOfURL: url!)

        1. 将网址绑定到您的imageView
        2. imageView.image = UIImage(data: data!)

          最终代码

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

答案 2 :(得分:3)

此代码适用于我

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
}

答案 3 :(得分:1)

absoluteString替换为path

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)

答案 4 :(得分:1)

此示例代码可能会为某些人打字,

将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)")

稍后阅读该图片......

..并将其转换回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")
    ...

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

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

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

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")
    }
}

答案 5 :(得分:1)

迅速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)
        }

答案 6 :(得分:0)

这对我有用,我认为这是一种快速,干净的方法。

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!)

其中“ imageUrl”是您在documents文件夹中的imageURL的值。而“图像”就是您可以在任何需要的地方使用的结果图像。

答案 7 :(得分:-2)

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

2.cell.image.sd_setIndicatorStyle(.gray)

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