ios 如何使用 writeToFile 将图像保存在文档目录中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32836862/
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 07:51:13  来源:igfitidea点击:

how to use writeToFile to save image in document directory?

iosimageswiftwritetofile

提问by Nishad Arora

// directoryPath is a URL from another VC
@IBAction func saveButtonTapped(sender: AnyObject) {
            let directoryPath           =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
            let urlString : NSURL       = directoryPath.URLByAppendingPathComponent("Image1.png")
            print("Image path : \(urlString)")
            if !NSFileManager.defaultManager().fileExistsAtPath(directoryPath.absoluteString) {
                UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.absoluteString, atomically: true)
                displayImageAdded.text  = "Image Added Successfully"
            } else {
                displayImageAdded.text  = "Image Not Added"
                print("image \(image))")
            }
        }

I am not getting any error but the Image is not getting saved in the document.

我没有收到任何错误,但图像没有保存在文档中。

回答by Leo Dabus

The problem there is that you are checking if the folder not exists but you should check if the file exists. Another issue in your code is that you need to use url.path instead of url.absoluteString. You are also saving a jpeg image using a "png" file extension. You should use "jpg".

问题在于您正在检查文件夹是否不存在,但您应该检查文件是否存在。您代码中的另一个问题是您需要使用 url.path 而不是 url.absoluteString。您还使用“png”文件扩展名保存 jpeg 图像。你应该使用“jpg”。

edit/update:

编辑/更新:

Swift 4.2 or later

Swift 4.2 或更高版本

// get the documents directory url
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = image.jpegData(compressionQuality:  1.0),
  !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        // writes the image data to disk
        try data.write(to: fileURL)
        print("file saved")
    } catch {
        print("error saving file:", error)
    }
}

回答by Roxana

This is my answer for Swift 3, combining the 2 answers above:

这是我对Swift 3 的回答,结合了上面的 2 个回答:

let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
// create a name for your image
let fileURL = documentsDirectoryURL.appendingPathComponent("Savedframe.png")


if !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        try UIImagePNGRepresentation(imageView.image!)!.write(to: fileURL)
            print("Image Added Successfully")
        } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
}

回答by daviddna

An extension method in swift 4.2

swift 4.2 中的扩展方法

import Foundation
import UIKit

extension UIImage {

    func saveToDocuments(filename:String) {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileURL = documentsDirectory.appendingPathComponent(filename)
        if let data = self.jpegData(compressionQuality: 1.0) {
            do {
                try data.write(to: fileURL)
            } catch {
                print("error saving file to documents:", error)
            }
        }
    }

}

回答by James Bush

Put the image in an NSData object; writing to a file with this class is a breeze, and it'll make the file size smaller.

将图像放入 NSData 对象中;用这个类写入文件是轻而易举的,它会使文件更小。

By the way, I recommend NSPurgeableData. After saving the image, you can mark the object as purgeable, which will keep memory consumption. That may be a problem with your app, but might be with another you're crowding out.

顺便说一下,我推荐 NSPurgeableData。保存图像后,您可以将对象标记为可清除,这将保持内存消耗。这可能是您的应用程序的问题,但可能是您排挤的另一个问题。

回答by Nishad Arora

@IBAction func saveButtonTapped(sender: AnyObject) {
let directoryPath           =  try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)    
let urlString : NSURL       = directoryPath.URLByAppendingPathComponent("Image1.png")
    print("Image path : \(urlString)")
    if !NSFileManager.defaultManager().fileExistsAtPath(urlString.path!) {
        UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.path! , atomically: true)
        displayImageAdded.text  = "Image Added Successfully"
    } else {
        displayImageAdded.text  = "Image Not Added"
        print("image \(image))")
    }
}

回答by iOS

In Swift 4.2 and Xcode 10.1

在 Swift 4.2 和 Xcode 10.1 中

func saveImageInDocsDir() {

    let image: UIImage? = yourImage//Here set your image
    if !(image == nil) {
        // get the documents directory url
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] // Get documents folder
        let dataPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("ImagesFolder").absoluteString //Set folder name
        print(dataPath)
        //Check is folder available or not, if not create 
        if !FileManager.default.fileExists(atPath: dataPath) {
            try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: true, attributes: nil) //Create folder if not
        }

        // create the destination file url to save your image
        let fileURL = URL(fileURLWithPath:dataPath).appendingPathComponent("imageName.jpg")//Your image name
        print(fileURL)
        // get your UIImage jpeg data representation
        let data = UIImageJPEGRepresentation(image!, 1.0)//Set image quality here
        do {
            // writes the image data to disk
            try data?.write(to: fileURL, options: .atomic)
        } catch {
            print("error:", error)
        }
    }
}

回答by Asad Ali Choudhry

Although the answers are correct, I want to share utility functions for this purpose. You can use the following 2 methods to save and Image in Documents Directory and then load an image from Documents Directory. Here you can find the Detailed Article.

虽然答案是正确的,但我想为此目的共享实用程序功能。您可以使用以下两种方法将图像保存在文档目录中,然后从文档目录中加载图像。在这里您可以找到详细文章

public static func saveImageInDocumentDirectory(image: UIImage, fileName: String) -> URL? {

        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        if let imageData = UIImagePNGRepresentation(image) {
            try? imageData.write(to: fileURL, options: .atomic)
            return fileURL
        }
        return nil
    }

public static func loadImageFromDocumentDirectory(fileName: String) -> UIImage? {

        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        do {
            let imageData = try Data(contentsOf: fileURL)
            return UIImage(data: imageData)
        } catch {}
        return nil
    }