2017-02-25 25 views
0

我目前正在设计一个Realm数据库管理应用程序,我已经成功地创建和检索了一个对象。我遇到的问题是更新/编辑 - 特别是更新用户上传的UIImage。借助Realm,我可以保存图像的路径,然后通过加载该路径(在文档目录中)来检索它。UIImageJPEGRepresentation | generateJPEGRepresentation将图像保存为零? Swift 3

当用户试图保存更改的图像时,出于某种奇怪的原因,UIImageJPEGRepresentation将更改的图像保存为零,从而删除用户的图像。这很奇怪,因为数据对象的初始创建存储它就好了。

我试图检查图像是否正在通过一些调试正确传递,并发现它这样做很好,正确的路径被保存。

这里是我的更新方法:

func updateImage() { 
    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 
    let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)") 

    if FileManager.default.fileExists(atPath: fileURL.path) { 
     do { 
      if profilePic.image != nil { 
      let image = profilePic.image!.generateJPEGRepresentation() 
      try! image.write(to: fileURL, options: .atomicWrite) 
      } 
     } catch { 
      print(error) 
     } 
    } else { 
      print("Image Not Added") 
    } 
} 

任何人都可以看到任何问题?

回答

1
let image = profilePic.image!.generateJPEGRepresentation() 

检查此行,无论它是否返回零值或数据?如果没有,那么使用下面的代码来测试你的图像存储,它的工作。同时确保您的实际图像具有JPEG文件格式扩展名,您正在尝试生成。

func getDocumentsDirectory() -> URL { 
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    let documentsDirectory = paths[0] 
    return documentsDirectory 
} 

//对PNG图像

if let image = UIImage(named: "example.png") { 
    if let data = UIImagePNGRepresentation() { 
     let filename = getDocumentsDirectory().appendingPathComponent("copy.png") 
     try? data.write(to: filename) 
    } 
} 

对于JPG图像

if let image = UIImage(named: "example.jpg") { 
    if let data = UIImageJPEGRepresentation(image, 1.0) { 
     let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg") 
     try? data.write(to: filename) 
    } 
} 
+0

您要保存JPEG数据表示为png格式 –

+0

是的,既会工作,我想告诉你, 尝试一下。 – 2017-02-25 02:15:59

+0

当然它会保存,但一个JPEG文件是一个JPEG文件。如果你想要一个PNG文件,你需要使用'UIImagePNGRepresentation' –