将NSImageView作为png / jpg保存到磁盘

时间:2018-02-19 02:17:43

标签: swift nsdata nsview nsfilemanager nsbitmapimagerep

我尝试根据(所有子视图)NSImageView的内容创建图像,并将其保存到Mac上的磁盘上。现在,将其写入磁盘的步骤失败了。当我逐步调试调试器中的代码时,我注意到imageData似乎没有正确创建。 “变量”视图将imageData的值显示为some,当我看得更深时,字段backing.bytesnil

enter image description here

我的猜测是这一行:

let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])

失败了。这是我正在使用的完整代码:

class ExportableImageView: NSImageView {

    func saveToDisk() {
        let rep: NSBitmapImageRep! = self.bitmapImageRepForCachingDisplay(in: self.bounds)
        self.cacheDisplay(in: self.bounds, to: rep!)

        let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
        let paths = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)
        let desktopPath = URL.init(string: paths[0])
        let savePath = desktopPath?.appendingPathComponent("test.png")
        do {
            try imageData!.write(to: savePath!, options: .atomic)
        }
        catch {
            print("save error")
        }
    }

    /* Other stuff */
}

为什么会失败的任何想法?感谢。

1 个答案:

答案 0 :(得分:0)

感谢Willeke的建议,我只需要改变我获取桌面路径的方式

let desktopPath = try! fileManager.url(for: .desktopDirectory, in: .allDomainsMask, appropriateFor: nil, create: true)

这是最终的解决方案

func saveToDisk() {
    let rep: NSBitmapImageRep! = self.bitmapImageRepForCachingDisplay(in: self.bounds)
    self.cacheDisplay(in: self.bounds, to: rep!)
    let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, properties: [:])

    let fileManager = FileManager.default
    let desktopPath = try! fileManager.url(for: .desktopDirectory, in: .allDomainsMask, appropriateFor: nil, create: true)            
    let filePath = desktopPath.appendingPathComponent("test.png")
    do {
        try imageData.write(to: filePath, options: .atomic)
    }
    catch {
        print("save file error: \(error)")
    }
}