如何保存图像 [英] How to save image

查看:115
本文介绍了如何保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用userdefaults保存图像并使用此代码在另一个视图中使用它,但它显示错误。

I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : "simg")

请帮帮我

推荐答案

我就是这样做的。你有多个地方可以保存它,用户的Documents文件夹通常是最好的:

This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:

func cacheImageAsPNG(image: UIImage, localID: String) {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    if let imageData = UIImagePNGRepresentation(image) {
        let filename = userDocumentsURL.appendingPathComponent("\(localID).png")

        if  FileManager.default.createFile(atPath: filename.path, contents: imageData, attributes: nil) {
            print("wrote file:\n\(filename.path)")
        } else {
            print("couldn't write the file:\n\(filename.path)")
        }
    }
}

如果您希望系统在系统中删除它高峰内存使用次数,缓存目录是一个更好的地方:

if you want it erased by the system during times of peak memory usage, the cache directory is a better place:

 let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!

编辑:检索图像

func cachedImage(localID: String) -> UIImage? {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let cachePath = userDocumentsURL.appendingPathComponent("\(localID).png")

    return UIImage(named: cachePath.path)
}

这篇关于如何保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆