如何通过Swift保存和加载文件图像 [英] How to save and load file image by swift

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

问题描述

我有UIImage(从解析中获取-转换变量PFFile). 如何从此变量保存和加载图像?

I have UIImage (got from Parse - convert variable PFFile). How can I save and load image from this variable?

  let a = object["image"] as! PFFile
  a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in
      if (error == nil) {
           // I have image, but the next I don't know what I do
           let image = UIImage(data:data!)
      }
   })

推荐答案

保存图像png

 func saveImage(image:UIImage,name:String){        
     let selectedImage: UIImage = image
     let data:NSData = UIImagePNGRepresentation(selectedImage)
     let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

     let success = fileManager.createFileAtPath(path, contents: data, attributes: nil)
     print(success)
     // Check image saved successfully
     let getImagePath = (path as NSString).stringByAppendingPathComponent(name)
     if fileManager.fileExistsAtPath(getImagePath) {
        // image save success
        let image = UIImage(contentsOfFile: getImagePath)!
     }
     else{
        // image save error
     }
}

保存其他文件

static func saveFile(fileData:NSData,name:String)->Bool{
    let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil)
    return success
}

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

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