Skip to content

Instantly share code, notes, and snippets.

@zlove
Forked from kamikat/image64.sh
Last active September 27, 2017 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zlove/677d24c02ebc3a253f1005bfe718b933 to your computer and use it in GitHub Desktop.
Save zlove/677d24c02ebc3a253f1005bfe718b933 to your computer and use it in GitHub Desktop.
Create data URI image from Terminal command
#! /usr/bin/env bash
# Examples:
# ./image64.sh myImage.png
# outputs: data:image/png;base64,xxxxx
# ./image64.sh myImage.png -img
# outputs: <img src="data:image/png;base64,xxxxx">
function usage {
echo "usage: $0 <image_filename> [--img]"
echo -e "\n image_filename\n A path to a gif, jpg, png or ico image"
echo -e "\n --img\n Output an html img tag"
}
if [ $# -eq 0 ]; then
echo "Error: No image file provided"
usage
exit 1
fi
filename=$(basename $1)
xtype=${filename##*.}
append=""
if [ ! -f "$1" ]; then
echo "Error: File does not exist"
usage
exit 1
fi
if [ $xtype == gif ]; then
append="data:image/gif;base64,";
elif [ $xtype == jpeg ] || [ $xtype == jpg ]; then
append="data:image/jpeg;base64,";
elif [ $xtype == png ]; then
append="data:image/png;base64,";
elif [ $xtype == svg ]; then
append="data:svg+xml;base64,";
elif [ $xtype == ico ]; then
append="data:image/vnd.microsoft.icon;base64,";
else
echo "Error: Unknown image type"
usage
exit 1
fi
#Mathias Bynens - http://superuser.com/questions/120796/os-x-base64-encode-via-command-line
data=$(openssl base64 < $1 | tr -d '\n')
if [ "$#" -eq 2 ] && [ $2 == -img ]; then
data=\<img\ src\=\"$append$data\"\>
else
data=$append$data
fi
echo $data | pbcopy
echo "copied to clipboard"
@zlove
Copy link
Author

zlove commented Sep 27, 2017

Added usage and basic checks for proper command line args

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment