1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Mac] イメージをクリップボードにコピーする impbcopy コマンド

Posted at

標準の pbcopyコマンドは、テキストをクリップボードにコピーしますが、イメージはコピーできません。
そこで、イメージをクリップボードにコピーする impbcopyコマンドを作ります。
とは言っても、自分のオリジナルではなく、GitHubに上がっていた Objective-C で書かれたコードを Swift に書き換えただけです。

Objective-Cで書かれた元のソースコードは、↓こちら。
(これをこのまま利用しても、もちろん 問題なく動作します)

https://gist.github.com/mwender/49609a18be41b45b2ae4
pbcopy.png

impbcopy コマンド

↓Swiftに書き換えたコードです。

impbcopy.swift
import Cocoa

func copy_to_clipboard(_ path: String) -> Bool {
    let image: NSImage?
    if path == "-" {
        let input = FileHandle.standardInput
        image = NSImage(data: try! input.readToEnd()!)
    } else {
        image = NSImage(contentsOfFile: path)
    }
    var copied = false
    if let image {
        let pasteboard = NSPasteboard.general
        pasteboard.clearContents()
        let copiedObjects = [image]
        copied = pasteboard.writeObjects(copiedObjects)
    }
    return copied
}

let main: () -> Bool = {
    guard CommandLine.arguments.count > 1 else {
        print("""
            Usage:\n
            Copy file to clipboard:\n    ./impbcopy path/to/file\n
            Copy stdin to clipboard:\n    cat /path/to/file | ./impbcopy -
            """)
        return false
    }
    
    let path = CommandLine.arguments[1]
    return copy_to_clipboard(path)
}

exit(main() ? EXIT_SUCCESS : EXIT_FAILURE)

ビルド

次のコマンドでビルド(コンパイル&リンカ)します。

コンパイル&リンカ
$ swiftc impbcopy.swift -o impbcopy

使い方

$ impbcopy
Usage:

Copy file to clipboard:
    ./impbcopy path/to/file

Copy stdin to clipboard:
    cat /path/to/file | ./impbcopy -

$ impbcopy sample.png

$ cat sample.png | impbcopy -

環境

執筆時の環境は以下の通り

$ uname -a
Darwin Mac-mini.local 23.4.0 Darwin Kernel Version 23.4.0: Wed Feb 21 21:44:06 PST 2024; root:xnu-10063.101.15~2/RELEASE_ARM64_T8103 arm64

$ swiftc --version
swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

以上です





追伸

ユニバーサルクリップボードの機能で、Mac ⬄ iPhone 間で自由にコピペできるのは、ホント便利ですね。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?