Skip to content

Instantly share code, notes, and snippets.

@ringtailsoftware
Last active January 4, 2023 22:46
Show Gist options
  • Select an option

  • Save ringtailsoftware/d435ddab7ed360409667aea0d5d7e0f7 to your computer and use it in GitHub Desktop.

Select an option

Save ringtailsoftware/d435ddab7ed360409667aea0d5d7e0f7 to your computer and use it in GitHub Desktop.
MacOS shell script to convert image in clipboard to HTML img tag containing data URL
#!/bin/bash
# https://codewithhugo.com/convert-image-data-url/
function img-data() {
TYPE=$(file --mime-type -b $1)
ENC=$(base64 $1)
echo -ne '<img src="'"data:$TYPE;base64,$ENC"'"/>'
}
# Convert image data in clipboard to file containing JPEG
TMPFILE=$(osascript \
-e 'set png_data to the clipboard as JPEG picture' \
-e 'set posixtmpfile to POSIX path of (path to temporary items folder) & "img_" & text 3 thru -1 of ((random number) as string)' \
-e 'set fhandle to open for access posixtmpfile with write permission' \
-e 'write png_data to fhandle' \
-e 'close access fhandle' \
-e 'return posixtmpfile as string') && \
# Convert JPEG file to data URL and place back in clipboard
img-data $TMPFILE | pbcopy - && \
# Cleanup tmp file
rm -f $TMPFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment