【发布时间】:2018-02-19 02:17:42
【问题描述】:
我正在尝试从(所有子视图)NSImageView 的内容创建图像并将其保存到 Mac 上的磁盘。现在将其写入磁盘的步骤失败了。当我单步调试调试器中的代码时,我注意到imageData 似乎没有正确创建。变量视图将imageData 的值显示为some,当我深入查看时,字段backing.bytes 是nil。
我的猜测是这一行:
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