2

When I take a screenshot on macOS, and use pngpaste a1.png to save it, the image is faded: enter image description here

This only happens when I take a fullscreen screenshot using CMD+SHIFT+3, and not with CMD+SHIFT+4.

2

1 Answer 1

3

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

Old answer (more minimal):

function pngpaste() {
    local name="${1}"

    [[ "$name" =~ '\.png$' ]] || name+=.png

    osascript -e "tell application \"System Events\" to ¬
                  write (the clipboard as «class PNGf») to ¬
                          (make new file at folder \"$(pwd)\" with properties ¬
                                  {name:\"${name}\"})"
}

function jpgpaste() {
    local name="${1}"

    [[ "$name" =~ '\.jpg$' ]] || name+=.jpg

    osascript -e "tell application \"System Events\" to ¬
                  write (the clipboard as JPEG picture) to ¬
                          (make new file at folder \"$(pwd)\" with properties ¬
                                  {name:\"${name}\"})"
}

Usage:

pngpaste a1.png
3
  • pngpaste also offers outputting the base64 of the image data (-b) flag, so this is not a full replacement, unfortunately. Nov 8, 2021 at 2:22
  • 1
    @MartinBraun Well, convert the image to base64 using some other tool. There are dozens of such encoders.
    – HappyFace
    Nov 8, 2021 at 14:54
  • Yes you are right, but as you might already know, I'd like to skip the output to the file system and go straight to base64 using stdout. Nov 14, 2021 at 12:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .