将NSImage保存到路径不起作用

时间:2017-11-03 13:16:17

标签: swift macos save nsfilemanager nsimage

我正在处理的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
    }
}

2 个答案:

答案 0 :(得分:0)

可能是因为沙箱。您的应用已获得通过“打开”对话框加载<folder>/originalfile.png的权限,但无权保存到<folder>/test.png。您需要向用户显示“保存”对话框(可以预先选择默认文件名)以获得保存新文件的权限。

答案 1 :(得分:0)