macOS: saving images from the clipboard using `pngpaste` is faded and white

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.


Solution 1:

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