Skip to content

Instantly share code, notes, and snippets.

@TurnerSoftwareDev
Created October 16, 2023 02:43
Show Gist options
  • Save TurnerSoftwareDev/01d0abdabf22810992d2ddc929b5d949 to your computer and use it in GitHub Desktop.
Save TurnerSoftwareDev/01d0abdabf22810992d2ddc929b5d949 to your computer and use it in GitHub Desktop.
Rotate an image either from a local file or a URL
#!/usr/bin/env bash
# Rotates an image from either a local file or from a URL passed on the command line or to stdin,
# and prints the rotated image file path to stdout.
#
# Positive angles rotate clockwise, negative counterclockwise.
# Exit on first error
set -e
validfile() { [[ -r ${1} ]]; }
validurl ()
{
# Read the first byte from the URL
if curl --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 convert # From Imagemagick
installed curl
output_file=
angle="90" # Default to rotating 90 degrees clockwise
while [[ $# != 0 ]]; do
case "${1}" in
-d|--degrees|--degree|-a|--angle)
angle="${2}"
shift 2
;;
-o|--output)
output_file="${2}"
shift 2
;;
*)
rotate_params+=("${1}")
shift
;;
esac
done
# Get the file path or URL from the command line argument or from stdin.
[[ ${#rotate_params[@]} -ge 1 ]] && input="${rotate_params[*]}" || input=$(cat)
if [[ -z ${input} ]]; then
>&2 echo "No file or URL was provided"
exit 1
fi
img_file=
if validfile "${input}"; then
img_file="${input}"
elif validurl "${input}"; then
tmpfile=$(mktemp /tmp/flip-img-XXXXXX)
curl --output "${tmpfile}" --silent "${input}"
# Add a file extension to the tmp file so the output file has the extension too.
ext=$(grep "$(file -b --mime-type "${tmpfile}")" /etc/mime.types | awk '{print $2}')
if [[ ! -z ${ext} ]]; then
mv "${tmpfile}" "${tmpfile}.${ext}"
tmpfile="${tmpfile}.${ext}"
fi
# 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
if [[ -z ${output_file} ]]; then
output_file=$(echo "${img_file}" | sed -E "s|(.*)(\..*)|\1_rotated\2|")
fi
convert -rotate "${angle}" "${img_file}" "${output_file}"
if [[ -r ${output_file} ]]; then
echo "${output_file}"
exit 0
else
>&2 echo "${output_file} was not created"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment