Swift 以png/jpg格式将NSImageView保存到磁盘
我正在尝试从Swift 以png/jpg格式将NSImageView保存到磁盘,swift,nsdata,nsview,nsfilemanager,nsbitmapimagerep,Swift,Nsdata,Nsview,Nsfilemanager,Nsbitmapimagerep,我正在尝试从NSImageView的(所有子视图)内容创建一个图像,并将其保存到Mac上的磁盘上。现在,将其写入磁盘的步骤失败了。在调试程序中逐步执行代码时,我注意到imageData似乎没有正确创建。变量视图将imageData的值显示为some,当我深入查看时,字段backing.bytes为nil 我猜是这样的: let imageData: Data! = rep!.representation(using: NSBitmapImageRep.FileType.png, propert
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 */
}
你知道为什么这会失败吗?谢谢。多亏了
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)")
}
}
您的应用程序可能已被沙盒。如果您希望能够从您的沙盒捆绑包位置保存任何内容,则需要显示NSSavePanel,让用户选择目标文件夹或禁用应用程序中的沙盒功能。我猜这行代码是:let savePath=desktopath?.appendingPathComponent(“test.png”)你不能只在你想要的任何地方创建一个文件。RDP从何而来,你为什么要强制解包呢?“你应该考虑使用FielMaGeer-Tror方法URL(O:I::)和URL(A:In:AuthAuto::CREATI::)返回URL,这是首选格式。