Skip to content

Instantly share code, notes, and snippets.

@TurnerSoftwareDev
Created October 16, 2023 01:18
Show Gist options
  • Save TurnerSoftwareDev/f2c143e2e84accc9abb8705ccc2175fa to your computer and use it in GitHub Desktop.
Save TurnerSoftwareDev/f2c143e2e84accc9abb8705ccc2175fa to your computer and use it in GitHub Desktop.
Upload images to Imgur from a file or URL
#!/usr/bin/env bash
# Uploads an image to imgur.com from either a local file or from a URL passed on the command line or to stdin,
# and prints the imgur.com URL to stdout.
#
# Examples:
#
# imgur foo.png
# imgur http://example.com/foo.jpg
# echo foo.png | imgur
# echo http://example.com/foo.jpg | imgur
# Exit on first error
set -e
# Debug
#set -x
validfile() { [[ -r ${1} ]]; }
validurl ()
{
# Read the first byte from the URL
if curl --insecure --output /dev/null --silent --fail -r 0-0 "${1}"; then
return 0
else
return 1
fi
}
installed () { command -v "${1}" >/dev/null 2>&1 || { >&2 echo "Cannot execute the ${1} command"; exit 1; } }
installed jq
installed curl
# Get the file path or URL from the command line argument or from stdin.
[[ $# -ge 1 ]] && input="${1}" || input=$(cat)
if [[ -z ${input} ]]; then
>&2 echo "No filename or was provided"
exit 1
fi
img_file=
if validfile "${input}"; then
img_file="${input}"
elif validurl "${input}"; then
# Download it to a tmp file.
tmpfile=$(mktemp /tmp/imgur-XXXXXX)
curl --insecure --location --output "${tmpfile}" --silent "${input}"
# Remove the tmp file when we're done.
trap 'rm -f ${tmpfile}' EXIT INT
img_file="${tmpfile}"
else
>&2 echo "${input} cannot be read"
exit 1
fi
content_type=$(file --brief --mime-type "${img_file}")
filename=$(basename -- "${img_file}")
curl --insecure -X POST "https://imgur.com/upload" \
-H "Referer: http://imgur.com/upload" \
-H "Accept: application/json" \
-F "Filedata=@\"${img_file}\";filename=${filename};type=${content_type}" \
| jq -r '.data | .hash, .ext' | xargs printf "https://i.imgur.com/%s%s\n"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment