This repository has been archived by the owner on Sep 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 93
/
convertToPng
executable file
·75 lines (64 loc) · 1.98 KB
/
convertToPng
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/bin/sh
# USAGE
# =====
# ./convertToPng <input.svg or input.png or input.ico> <output.png> <square edge size (optional, defaults to 1024 px)>
# Example:
# ./convertToPng ~/icon.png ~/Desktop/icon_converted.png 512
# Exit the shell script on error immediately
set -e
# Check for dependencies
if [ "${SOURCE_EXT}" == "png" ]; then
# imagemagick
type identify >/dev/null 2>&1 || { echo >&2 "Cannot find required ImageMagick Identify executable"; exit 1; }
type convert >/dev/null 2>&1 || { echo >&2 "Cannot find required ImageMagick Convert executable"; exit 1; }
elif [ "${SOURCE_EXT}" == "svg" ]; then
# CairoSVG
type cairosvg >/dev/null 2>&1 || { echo >&2 "Cannot find required CairoSVG executable"; exit 1; }
fi
# Arguments
SOURCE=$1
DEST=$2
SIZE=$3
# Check arguments
if [ -z "${SOURCE}" ]; then
echo "No source image specified"
exit 1
fi
if [ -z "${DEST}" ]; then
echo "No destination specified"
exit 1
fi
if [ -z "${SIZE}" ]; then
# Set default size to 1024 px
SIZE=1024
fi
# File variables
SOURCE_NAME=$(basename "${SOURCE}")
SOURCE_EXT="${SOURCE_NAME##*.}"
SOURCE_BASE="${SOURCE_NAME%.*}"
# Temp directory
TEMP_DIR=".convertToPng"
mkdir -p "${TEMP_DIR}"
# Cleanup
function cleanUp() {
rm -rf "${TEMP_DIR}"
}
trap cleanUp EXIT
# Check for file type
if [ "${SOURCE_EXT}" == "svg" ]; then
cairosvg "${SOURCE}" "--output-width=${SIZE}" "--output-height=${SIZE}" "--output=${DEST}"
elif [ "${SOURCE_EXT}" == "png" ] || [ "${SOURCE_EXT}" == "ico" ]; then
# Check if .ico is a sequence
# Pipe into cat so no exit code is given for grep if no matches are found
IS_ICO_SET="$(identify ${SOURCE} | grep -e "\w\.ico\[0" | cat )"
convert "${SOURCE}" -define png:big-depth=16 -define png:color-type=6 -sample "${SIZE}x${SIZE}" "${TEMP_DIR}/${SOURCE_BASE}.png"
if [ "${IS_ICO_SET}" ]; then
# Extract the largest (?) image from the set
cp "${TEMP_DIR}/${SOURCE_BASE}-0.png" "${DEST}"
else
cp "${TEMP_DIR}/${SOURCE_BASE}.png" "${DEST}"
fi
else
echo "SVG, PNG or ICO must be provided"
exit 1
fi