【问题标题】:Save NSImageView to disk as png/jpg将 NSImageView 以 png/jpg 格式保存到磁盘
【发布时间】:2018-02-19 02:17:42
【问题描述】:

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

我的猜测是这一行:

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 */
}

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

【问题讨论】:

  • 你的应用可能是沙盒的。如果您希望能够从沙盒捆绑位置保存任何内容,则需要提供 NSSavePanel 以让用户选择目标文件夹或在您的应用功能中禁用沙盒
  • 我猜是这一行:let savePath = desktopPath?.appendingPathComponent("test.png")
  • 你不能随便在任何地方创建文件。
  • rep 从哪里来,为什么要强制解包?
  • “您应该考虑使用 FileManager 方法 urls(for:in:) 和 url(for:in:appropriateFor:create:)。它们返回 URL,这是首选格式。”

标签: swift nsdata nsview nsfilemanager nsbitmapimagerep


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多