[英]How to copy image or file to clipboard using JXA?
我在 ScriptEditor 中使用 JavaScript 有困难
AppleScript 像这样通过路径复制图像到剪贴板
set image to POSIX file ("/Users/lll00lll/Library/Documents/temp.jpg")
set the clipboard to image
但是如何将上面的AppleScript编码翻译成JavaScript呢?
JavaScript 这样可以将字符串复制到剪贴板但不能复制图像或文件
var app = Application('Script Editor');
app.includeStandardAdditions = true;
app.setTheClipboardTo(str);
或使用 Objective-C?但我不知道如何将其编辑为“generalPasteboard.setData”
$.NSPasteboard.generalPasteboard.clearContents;
$.NSPasteboard.generalPasteboard.setStringForType($(str), $.NSPasteboardTypeString);
这使用 JS-ObjC 桥将一个或多个文件放到剪贴板上。 fsCopy
可以传递单个文件路径或文件路径数组,并在操作完成后返回剪贴板上的项目数(显然,这应该等于文件路径数)。
ObjC.import('AppKit');
function fsCopy(fs) {
const pb = $.NSPasteboard.generalPasteboard;
pb.clearContents;
[].concat(fs).forEach(f =>
pb.writeObjects([
ObjC.unwrap($.NSURL
.fileURLWithPath(f))
])
);
return pb.pasteboardItems.count * 1;
}
稍微简化CJK 的回答:
// makes Cocoa NS* classes available under $
ObjC.import('AppKit'); // same as ObjC.import('Cocoa');
// necessary to get correct result, but I'm not sure why
$.NSPasteboard.generalPasteboard.clearContents;
// create a Cocoa URL for the file system item
const nsUrl = $.NSURL.fileURLWithPath('/Users/lll00lll/Library/Documents/temp.jpg');
// set the pasteboard to the URL
// .js unwraps the NSUrl reference for use in Obj-C
$.NSPasteboard.generalPasteboard.writeObjects([nsUrl.js]);
说明
在原始问题中,AppleScript 片段将文件的剪贴板设置为URL 。 JSX 片段将剪贴板设置为UTF 字符串。 我尝试使用 JSX Path()
类型,但它会将剪贴板设置为无意义的风格。
该答案手动创建一个 Cocoa URL 并将粘贴板设置为该值。
writeObjects()
方法也将接受NSImage
,因此您可以在 memory 中传递图像(尽管它比传递对文件的引用要慢):
const nsImage = $.NSImage.alloc.initByReferencingFile('/Users/lll00lll/Library/Documents/temp.jpg');
$.NSPasteboard.generalPasteboard.writeObjects([nsImage.js]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.