How can I Pbpaste an image in to the command line?
Current use case:
- I select "copy image" on some random png in safari.
- I type pbpaste into terminal, and get the link to the image.
Is there anyway to get the binary data instead?
Solution 1:
There is a utility just for your use case: pngpaste
https://github.com/jcsalterego/pngpaste
You can install (a bit older) version using brew install pngpaste
, or just git clone/make latest version.
Solution 2:
When you copy an image, OS X actually doesn't copy just the raw image data. In fact, there exist multiple pasteboards in Cocoa, in which there are multiple representations of your image.
Your only options with pbpaste
are to choose which pasteboard to access, but not which type of content. While the raw hexadecimal NSData
is stored somewhere in the pasteboard to be pasted to image editing tools, you can't pbpaste
it to a terminal which would only accept text. From the pbpaste
manpage:
It normally looks first for plain text data in the pasteboard and writes that to the standard output
Since plain text data is available as the image's URL, you'll always paste that, no matter what.
There is no way to tell pbpaste to get only a specified data type.
And just for completeness, here's the URL stored for an image, for example:
Screenshot taken with Pasteboard Inspector.
Solution 3:
Copied from my answer here.
You need to have gmktemp
(GNU mktemp
) installed. (Using, e.g., brew install coreutils
.)
The following is zsh
code; It might or might not work with bash
.
pngpaste () {
local name="${1}" extension="${2:-png}" class="${3}"
test -z "$class" && class='«class PNGf»'
local stdout=''
if [[ "$name" == '-' ]]
then
name="$(gmktemp --suffix ".${extension}")" || return $?
stdout=y
fi
local dir
dir="$(dirname "$name")"
if test -z "$dir"
then
dir="$PWD"
fi
dir="$(realpath "$dir")"
mkdir -p "$dir" || return $?
name="$(basename "$name")"
if test -z "${name}"
then
name+="some" || return $?
fi
[[ "$name" =~ '\.'${extension}'$' ]] || name+=".${extension}"
local f="${dir}/${name}"
if test -e "$f"
then
command rm "$f"
fi
osascript -e "tell application \"System Events\" to ¬
write (the clipboard as ${class}) to ¬
(make new file at folder \"${dir}\" with properties ¬
{name:\"${name}\"})" || return $?
if test -n "$stdout"
then
cat "$f"
command rm "$f"
fi
}
Usage:
pngpaste some_path.png
pngpaste - | base64