macOSでClipboardの画像を保存する
更新日:2020.07.16
作成日:2019.01.03
Visual Studio Code Extensionを作成するために、調べた結果をまとめます。
macOSでClipboard操作について分かったこと
- pbpasteではImageをペーストできない(Textのみ)
- Electronには、clipboardのAPIが存在するが Visual Studio Code からは(まだ)利用できないっぽい
対応方法
- 1.AppleScriptを利用する
- 2.Electron APIを利用する- njleonzhang/vscode-extension-mardown-image-paste: read the image from system clipborad, optimize the size, upload to CDN, and return you the CDN link.
のExtensionを見ると、Electron APIを利用してやりたいことがほぼできているのだが、electron-image-ipc-serverを別途動かしておかないといけない
 
- njleonzhang/vscode-extension-mardown-image-paste: read the image from system clipborad, optimize the size, upload to CDN, and return you the CDN link.
のExtensionを見ると、Electron APIを利用してやりたいことがほぼできているのだが、
- 3.pngpasteを利用する
Visual Studio CodeのExtension内で完結しないのはいかがなものかと思い、「1.AppleScriptを利用する」で実装することにしました。
AppleScriptでClipboradの画像をpng保存する
そういえば、AppleScriptを書いたことがなかったので、調べながら書きました。基本的には次のコードを参考にさせていただき作成しました。
mushanshitiancai/vscode-paste-image: paste image from clipboard to markdown/asciidoc directly!
下記の想定です。
- pngのファイルタイプを定義
- Clipboardにpng形式が含まれている場合は、引数として渡されたファイル名で保存
filetypeについては、
ASH Planning: クリップボード活用のススメ
をご覧ください。
property fileTypes : {{<class PNGf>, ".png"}}
 
on run argv
if argv is {} then
    return ""
end if
set theType to getType()
if theType is missing value then
    return "no image"
end if
set imagePath to (item 1 of argv)
try
    set myFile to (open for access imagePath with write permission)
    set eof myFile to 0
    write (the clipboard as (first item of theType)) to myFile
    close access myFile
    return (POSIX path of imagePath)
on error
    try
        close access myFile
    end try
    return ""
end try
end run
on getType()
repeat with aType in fileTypes
    repeat with theInfo in (clipboard info)
        if (first item of theInfo) is equal to (first item of aType) then return aType
    end repeat
end repeat
return missing value
end getTypecmd + shift + ctl + 4でスクリーンショットを取得した後、上記AppleScriptをspawnから実行すると、先ほど取得したスクリーンショットが画像として保存されます。
import { spawn } from 'child_process';
const scriptPath = path.join(__dirname, '../script/mac.applescript');
const filepath = 'save_to_dir';
let ascript = spawn('osascript', [scriptPath, filepath]);
ascript.stdout.on('data', (data) => {
    console.log(data.toString().trim()); // filename
});
            
ascript.stderr.on('data', (data) => {
    console.error(data);
});
ascript.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});参考
Related contents

TECH
2020.06.23
macOSでXcodeを利用せずにHomebrewを利用する方法

TECH
2020.01.14
VS Codeにtextlintを導入して文章を校正する

TECH
2017.04.30
macOS Sierraクリーンインストール時に行ったこと