保存图像然后加载到Swift(iOS)

保存图像然后加载到Swift(iOS),第1张

概述我正在使用saveImage保存图像. func saveImage (image: UIImage, path: String ) -> Bool{ let pngImageData = UIImagePNGRepresentation(image) //let jpgImageData = UIImageJPEGRepresentation(image, 1.0) // 我正在使用saveImage保存图像.
func saveImage (image: UIImage,path: String ) -> Bool{    let pngImageData = UIImagePNGRepresentation(image)    //let jpgImageData = UIImageJPEGRepresentation(image,1.0)   // if you want to save as JPEG    print("!!!saving image at:  \(path)")    let result = pngImageData!.writetofile(path,atomically: true)    return result}

新信息:

保存文件无法正常工作(打印“[ – ] ERROR SAVING file”) –

// save your image here into document Directory        let res = saveImage(tempImage,path: fileIndocumentsDirectory("abc.png"))        if(res == true){            print ("[+] file SAVED")        }else{            print ("[-] ERROR SAVING file")        }

为什么saveImage函数没有保存图像?访问权?

旧信息:

调试信息说:

!!!saving image at:  file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/documents/tempImage

然后我使用检索此位置

fileIndocumentsDirectory("tempImage")

结果是正确的.

然后我使用此路径加载文件

let image = UIImage(contentsOffile: path)    if image == nil {        print("missing image at: \(path)")    }else{        print("!!!IMAGE FOUND at: \(path)")    }

路径是正确的,但消息是“在…处丢失图像”.文件是否以某种方式无法访问或未存储?这种行为可能是什么原因?

我正在使用ios 7和带有ios 7模拟器的iphone 5在iphone 4上测试此代码.

编辑:
1. fileIndocumentsDirectory函数

func fileIndocumentsDirectory(filename: String) -> String {    let documentsURL = NSfileManager.defaultManager().URLsForDirectory(.documentDirectory,inDomains: .UserDomainMask)[0]    let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString    return fileURL        }
@H_301_39@ 斯威夫特3

此功能将图像保存在文档文件夹中:

func saveImage(image: UIImage) -> Bool {    guard let data = UIImageJPEGRepresentation(image,1) ?? UIImagePNGRepresentation(image) else {        return false    }    guard let directory = try? fileManager.default.url(for: .documentDirectory,in: .userDomainMask,appropriateFor: nil,create: false) as NSURL else {        return false    }    do {        try data.write(to: directory.appendingPathComponent("filename.png")!)        return true    } catch {           print(error.localizedDescription)        return false    }}

使用:

let success = saveImage(image: UIImage(named: "image.png")!)

这个函数将获得该图像:

func getSavedImage(named: String) -> UIImage? {    if let dir = try? fileManager.default.url(for: .documentDirectory,create: false) {        return UIImage(contentsOffile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)    }    return nil}

使用:

if let image = getSavedImage(named: "filename") {    // do something with image}
总结

以上是内存溢出为你收集整理的保存图像然后加载到Swift(iOS)全部内容,希望文章能够帮你解决保存图像然后加载到Swift(iOS)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1051486.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存