-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathautomark
executable file
·278 lines (234 loc) · 9.53 KB
/
automark
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/bin/bash
#=======================================================================================================================
# Description
# Script for automated watermarking of images
# Requires
# ImageMagick
# webp (apt install webp) for WebP support
# jpegoptim (apt install jpegoptim) for JPEG optimisation support
# OptiPNG (apt install optipng) for PNG optimisation support
# Synopsis
# automark [options] image_file_or_dir
#=======================================================================================================================
. "$(dirname "$(realpath "$0")")/common.sh"
# Setup vars
pic_size=1600 # Max size of the pictures
jpeg_quality=50 # Max quality for JPEG optimisation
file_watermark_white="$HOME/Pictures/Misc/dk-watermark-white.png" # Default watermark file
file_watermark_black="$HOME/Pictures/Misc/dk-watermark-black.png" # Black watermark file
file_watermark_small="$HOME/Pictures/Misc/dk-watermark-small.png" # 'Small' watermark file
USAGE_INFO="Usage: $0 [options] image_file_or_dir
Options:
-O Do not optimise JPEGs/PNGs
-R Do not resize photos to $pic_size pixels
-W Do not watermark images
-b Use black watermark instead of the default white one
-d Delete original (after successful processing)
-p Convert the image into WebP
-s Use "small" watermark instead of the default one (better for small images)"
#-----------------------------------------------------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------------------------------------------------
# Prints out a status message (overwritten every time)
# Arguments:
# $1 message text
status() {
# Pad/truncate the line to fit screen width
printf "%-${tty_width}.${tty_width}s\r" "$1"
}
# Prints out a progress message
# Arguments:
# $1 current item number
# $2 total number of items
# $3 message text
progress() {
printf -v msg '[%d/%d] %s' "$1" "$2" "$3"
status "$msg"
}
# Fetches image details using its metadata. Return success/error code
# Arguments:
# $1 image file name
fetch_image_details() {
# Fetch image size
img_size=$(identify -quiet -format "%w %h" "$1" | awk '{print ($1>$2 ? $1 : $2)}') || warn "Determining image size in $1 failed."
}
#=======================================================================================================================
# Main routine
#=======================================================================================================================
# Trap Ctrl-C
trap interrupted INT
#-----------------------------------------------------------------------------------------------------------------------
# Parse and check the command line
#-----------------------------------------------------------------------------------------------------------------------
# Parse command line options
b_delete_original=0
b_webp=0
b_resize=1
b_watermark=1
b_optimise=1
s_watermark_to_use="$file_watermark_white"
args=$(getopt -o BDORUWbdps -- "$@")
[[ $? -ne 0 ]] && usage
eval set -- $args
for i; do
case "$i" in
-O)
b_optimise=0
shift
;;
-R)
b_resize=0
shift
;;
-W)
b_watermark=0
shift
;;
-b)
s_watermark_to_use="$file_watermark_black"
shift
;;
-d)
b_delete_original=1
shift
;;
-p)
b_webp=1
shift
;;
-s)
s_watermark_to_use="$file_watermark_small"
shift
;;
--)
shift;
break
;;
esac
done
# Parse the rest of the command line
path_source="$(realpath "$1")"
# Check photos_dir
[[ -n "$path_source" ]] || usage "Source image file/directory is not specified"
[[ -e "$path_source" ]] || err "Source image file/directory '$path_source' does not exist."
#-----------------------------------------------------------------------------------------------------------------------
# Initialization
#-----------------------------------------------------------------------------------------------------------------------
# Get TTY width
tty_width=$(stty size | cut -d ' ' -f 2)
#-----------------------------------------------------------------------------------------------------------------------
# Read the file list
#-----------------------------------------------------------------------------------------------------------------------
# Get the file(s). If source is a dir
if [[ -d "$path_source" ]]; then
# Temporarily change the field separator to make find results work with filenames containing spaces
old_ifs=$IFS
IFS=$'\n'
# Scan for files
files=( $(find "$path_source" -type f \( -iname '*.jpg' -o -iname '*.png' -o -iname '*.webp' \) ! -name '*.amark.*' -print | sort) )
# Restore the field separator
IFS=$old_ifs
# Make sure target dir is (re)created
dir_target="$path_source.automark"
[[ -d "$dir_target" ]] && (rm -rf "$dir_target" || err "Failed to remove target directory $dir_target")
mkdir -p "$dir_target" || err "Failed to create target directory $dir_target"
# Otherwise verify it's a file
elif [[ ! -f "$path_source" ]]; then
err "$path_source is neither a directory nor a file"
# It's definitely a file
else
# Verify the extension
ext="$(echo ${path_source##*.} | tr '[:upper:]' '[:lower:]')"
[[ "$ext" != "jpg" ]] && [[ "$ext" != "png" ]] && [[ "$ext" != "webp" ]] && err "Unsupported image file extension: '$ext'"
files=("$path_source")
# Target file will reside in the same directory as the source
dir_target="$(dirname "$path_source")"
fi
i_count=${#files[@]}
#-----------------------------------------------------------------------------------------------------------------------
# Process the picture files
#-----------------------------------------------------------------------------------------------------------------------
# Iterate through the file list
i_cur_num=0
i_err_count=0
failed_pics=()
for (( i_cur_num=1; i_cur_num<=${i_count}; i_cur_num++ )); do
src_file=${files[$((i_cur_num-1))]}
b_error=0
# Determine full output file name
src_file_name=$(basename "$src_file")
src_extension="$(echo ${src_file##*.} | tr '[:upper:]' '[:lower:]')"
if [[ $b_webp -eq 0 ]]; then
dst_extension="$src_extension"
else
dst_extension=webp
fi
dst_file="$dir_target/${src_file_name%\.*}.amark.$dst_extension"
# Create a temporary PNG file for processing
tmp_file="$(mktemp).png"
# Print out status message
progress $i_cur_num $i_count "Processing $src_file"
# Try to fetch image details
fetch_image_details "$src_file"
# Determine the need for resize. We resize unless it's turned off, and only if picture size is unknown or bigger than
# the standard size
unset s_resize_flags
[[ $b_resize -ne 0 ]] && ( [[ -z "$img_size" ]] || [[ $img_size -gt $pic_size ]] ) && s_resize_flags="-resize ${pic_size}x${pic_size}"
# Resize and autorotate the image
if ! convert $s_resize_flags -quiet -quality 96 -auto-orient "$src_file" "$tmp_file"; then
b_error=1
warn "Conversion of $src_file into $tmp_file failed."
# Apply watermark
elif ! ( [[ $b_watermark -eq 0 ]] || composite -dissolve 90% -gravity southeast "$s_watermark_to_use" "$tmp_file" "$tmp_file" ); then
b_error=1
warn "Watermarking $src_file failed."
# If the format stays PNG, just move the created file into the final destination
elif [[ "$dst_extension" == "png" ]]; then
mv "$tmp_file" "$dst_file" || (b_error=1 && warn "Failed to move $tmp_file to $dst_file")
# Otherwise convert it to the target format
elif ! convert "$tmp_file" "$dst_file"; then
b_error=1
warn "Failed to convert $tmp_file into $dst_file"
fi
# Optimise the file if needed
if [[ $b_error -eq 0 ]] && [[ $b_optimise -ne 0 ]]; then
progress $i_cur_num $i_count "Optimising $src_file"
case "$dst_extension" in
jpg)
if ! jpegoptim --force --max=$jpeg_quality --quiet --strip-all "$dst_file"; then
b_error=1
warn "Failed to JPEG-optimise $dst_file"
fi
;;
png)
if ! optipng -quiet -o 7 "$dst_file"; then
b_error=1
warn "Failed to PNG-optimise $dst_file"
fi
;;
esac
fi
# If processing succeeded
if [[ $b_error -eq 0 ]]; then
# Delete the original if needed
[[ $b_delete_original -ne 0 ]] && (rm -f "$src_file" || warn "Couldn't delete $src_file")
# Otherwise add the picture to the failure list
else
failed_pics[$i_err_count]="$src_file"
((i_err_count++))
fi
# Remove temp file
rm -f "$tmp_file"
done
# If there were errors, print out failure list
if [[ $i_err_count -gt 0 ]]; then
warn "There were errors processing following pictures:"
for f in ${failed_pics[@]}; do echo "$f" >&2; done
fi
#-----------------------------------------------------------------------------------------------------------------------
# Finalization
#-----------------------------------------------------------------------------------------------------------------------
status "Done. $i_count files processed."
echo
[[ $i_err_count -gt 0 ]] && exit 1
exit 0