【问题标题】:UIImageJPEGRepresentation | generateJPEGRepresentation saves image as nil? Swift 3UIImageJPEG 表示 | generateJPEGRepresentation 将图像保存为零?斯威夫特 3
【发布时间】:2017-02-25 01:52:44
【问题描述】:

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

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

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

这是我的更新方法:

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")
    }
}

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

【问题讨论】:

    标签: ios swift swift3 nsdata uiimagejpegrepresentation


    【解决方案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)
        }
    }
    

    【讨论】:

    • 您正在将 jpeg 数据表示保存为 png
    • 是的,两者都可以,我想给你看,试试看。
    • 当然会保存,但 jpeg 就是 jpeg。如果你想要一个 png 文件,你需要使用 UIImagePNGRepresentation
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多