将 NSImage 保存到路径不起作用
Posted
技术标签:
【中文标题】将 NSImage 保存到路径不起作用【英文标题】:Saving NSImage to path doesn't work 【发布时间】:2017-11-03 13:16:17 【问题描述】:我正在开发的 macOS 程序通过对话框加载图像,然后裁剪并预览给用户。它现在应该将图像保存回最初加载它的路径的文件夹。我尝试通过.write(to: URL)
方法和NSFileManager 保存图像数据。也没有用。
输出:
file:///Users/username/Downloads/test.png
File creation failed
代码:
@IBAction func browseFile(_ sender: NSButton)
let dialog = NSOpenPanel();
dialog.title = "Choose an image file";
dialog.showsResizeIndicator = true;
dialog.showsHiddenFiles = false;
dialog.canChooseDirectories = true;
dialog.canCreateDirectories = true;
dialog.allowsMultipleSelection = true;
dialog.allowedFileTypes = ["jpg","jpeg","png"];
if (dialog.runModal() == NSApplication.ModalResponse.OK)
let result = dialog.url // Pathname of the file
if (result != nil)
// "result" is the path of the image selected via the dialog
let corrected: NSImage = cutImage(image: NSImage(contentsOf: result!)!) // crop image
imageView.image = corrected // show cropped image preview
// save cropped image to disk
let fileName = "test"
let fileManager = FileManager.default
let fileURL = result!.deletingLastPathComponent().appendingPathComponent("\(fileName).png") // set url to the same folder as where the image was loaded from
print(fileURL)
if let pngImageData = corrected.PNGRepresentation
//try? pngImageData.write(to: fileURL, options: .atomic)
fileManager.createFile(atPath: fileURL.path, contents: pngImageData, attributes: nil)
if fileManager.fileExists(atPath: fileURL.path)
print("File successfully saved")
else
print("File creation failed")
else
// User clicked on "Cancel"
return
【问题讨论】:
查看目标 > 应用沙盒 > 文件访问。 这成功了!感谢您的帮助 【参考方案1】:Enabling Read-Write Permissions in Capabilities -> File Access solved the problem
【讨论】:
【参考方案2】:可能是由于沙盒。您的应用获得了通过“打开”对话框加载 <folder>/originalfile.png
的权限,但无权保存到 <folder>/test.png
。您需要向用户显示保存对话框(可以预先选择默认文件名)以获得保存新文件的权限。
【讨论】:
以上是关于将 NSImage 保存到路径不起作用的主要内容,如果未能解决你的问题,请参考以下文章
java - trustStore 的路径 - 设置属性不起作用?