退出并加载我的应用程序时,如何将图像保存并读取到临时文件夹

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了退出并加载我的应用程序时,如何将图像保存并读取到临时文件夹相关的知识,希望对你有一定的参考价值。

当我的应用程序关闭时,我想保存并读取我的临时文件夹的UIImage,然后在应用程序加载时加载并删除它。我该如何做到这一点。请帮忙。

答案

这些方法允许您从iphone上的文档目录中保存和检索图像

+ (void)saveImage:(UIImage *)image withName:(NSString *)name {
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
    [fileManager createFileAtPath:fullPath contents:data attributes:nil];
}

+ (UIImage *)loadImage:(NSString *)name {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];    
    UIImage *img = [UIImage imageWithContentsOfFile:fullPath];

    return img;
}
另一答案

Swift 3 xCode 8.2

文件目录获取:

func getDocumentDirectoryPath() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory as NSString
}

保存:

func saveImageToDocumentsDirectory(image: UIImage, withName: String) -> String? {
    if let data = UIImagePNGRepresentation(image) {
        let dirPath = getDocumentDirectoryPath()
        let imageFileUrl = URL(fileURLWithPath: dirPath.appendingPathComponent(withName) as String)
        do {
            try data.write(to: imageFileUrl)
            print("Successfully saved image at path: (imageFileUrl)")
            return imageFileUrl.absoluteString
        } catch {
            print("Error saving image: (error)")
        }
    }
    return nil
}

加载:

func loadImageFromDocumentsDirectory(imageName: String) -> UIImage? {
    let tempDirPath = getDocumentDirectoryPath()
    let imageFilePath = tempDirPath.appendingPathComponent(imageName)
    return UIImage(contentsOfFile:imageFilePath)
}

例:

//TODO: pass your image to the actual method call here:
let pathToSavedImage = saveImageToDocumentsDirectory(image: imageToSave, withName: "imageName.png")
if (pathToSavedImage == nil) {
    print("Failed to save image")
}

let image = loadImageFromDocumentsDirectory(imageName: "imageName.png")
if image == nil {
    print ("Failed to load image")
}
另一答案

此外,您不希望在应用程序关闭后将任何内容保存到您想要的实际tmp目录中。 tmp目录可以由系统清除。根据定义,它仅存在于仅在应用程序运行时保存所需的次要文件。

您要保留的文件应始终进入documents目录。

另一答案

测试代码为swift

//to get document directory path
    func getDocumentDirectoryPath() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

打电话使用

if let data = UIImagePNGRepresentation(img) {
     let filename = self.getDocumentDirectoryPath().stringByAppendingPathComponent("resizeImage.png")
     data.writeToFile(filename, atomically: true)
}
另一答案

针对所选答案的Untested Swift调整:

class func saveImage(image: UIImage, withName name: String) {
    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    var data: NSData = UIImageJPEGRepresentation(image, 1.0)!
    var fileManager: NSFileManager = NSFileManager.defaultManager()

    let fullPath = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name)
    fileManager.createFileAtPath(fullPath.absoluteString, contents: data, attributes: nil)
}

class func loadImage(name: String) -> UIImage {
    var fullPath: String = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name).absoluteString
    var img:UIImage = UIImage(contentsOfFile: fullPath)!
    return img
}
另一答案

Swift 4实现:

// saves an image, if save is successful, returns its URL on local storage, otherwise returns nil
func saveImage(_ image: UIImage, name: String) -> URL? {
    guard let imageData = UIImageJPEGRepresentation(image, 1) else {
        return nil
    }
    do {
        let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name)
        try imageData.write(to: imageURL)
        return imageURL
    } catch {
        return nil
    }
}

// returns an image if there is one with the given name, otherwise returns nil
func loadImage(withName name: String) -> UIImage? {
    let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(name)
    return UIImage(contentsOfFile: imageURL.path)
}

用法示例(假设我们有一个图像):

let image = UIImage(named: "milan")

let url = saveImage(image, name: "savedMilan.jpg")
print(">>> URL of saved image: (url)")

let reloadedImage = loadImage(withName: "savedMilan.jpg")
print(">>> Reloaded image: (reloadedImage)")

以上是关于退出并加载我的应用程序时,如何将图像保存并读取到临时文件夹的主要内容,如果未能解决你的问题,请参考以下文章

如何加载保存到我的标记 ID 的图像并显示在该特定标记的自定义信息窗口中?

在退出 C++ 时保存值 [关闭]

保存一个 Object[][] 并加载它

保存并读取图像,但打开文件夹时找不到

如何使用 Glide 将图像保存到内部存储?

在 JPG 图像中隐藏消息