generated from pforret/bashew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
splashmark.sh
executable file
·1740 lines (1602 loc) · 57.7 KB
/
splashmark.sh
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
### Created by Peter Forret ( pforret ) on 2020-09-28
script_version="0.0.0" # if there is a VERSION.md in this script's folder, it will take priority for version number
readonly script_author="peter@forret.com"
readonly script_created="2020-09-28"
readonly script_description="Mark up images (unspash/pixabay/URL) with titles, effects and resize"
readonly run_as_root=-1 # run_as_root: 0 = don't check anything / 1 = script MUST run as root / -1 = script MAY NOT run as root
function Option:config() {
grep <<<"
#commented lines will be filtered
flag|h|help|show usage
flag|q|quiet|no output
flag|v|verbose|output more
option|l|log_dir|folder for log files |$HOME/log/$script_prefix
option|t|tmp_dir|folder for temp files|/tmp/$script_prefix
option|w|width|image width for resizing|1200
option|c|crop|image height for cropping|0
option|s|preset|image size preset
option|S|resize|multiply preset with factor
option|1|northwest|text to put in left top|
option|2|northeast|text to put in right top|{url}
option|3|southwest|text to put in left bottom|Created with pforret/splashmark
option|4|southeast|text to put in right bottom|{copyright2}
option|d|randomize|take a random picture in the first N results|1
option|D|number|take the Nth picture from query results|1
option|e|effect|use effect chain on image: bw/blur/dark/grain/light/median/paint/pixel|
option|g|gravity|title alignment left/center/right|center
option|i|title|big text to put in center|
option|z|titlesize|font size for title|80
option|k|subtitle|big text to put in center|
option|j|subtitlesize|font size for subtitle|50
option|m|margin|margin for watermarks|30
option|o|fontsize|font size for watermarks|15
option|p|fonttype|font type family to use|FiraSansExtraCondensed-Bold.ttf
option|r|fontcolor|font color to use|FFFFFF
option|x|photographer|photographer name (empty: use name from API)|
option|u|url|photo URL override (empty: use URL from API)|
option|P|PIXABAY_ACCESSKEY|Pixabay access key|
option|U|UNSPLASH_ACCESSKEY|Unsplash access key|
option|R|REPLICATE_ACCESSKEY|Replicate API key|
option|X|EXPORT|export to subfolder|export
option|E|EXTENSION|image extension to use|jpg
choice|1|action|action to perform|unsplash,pixabay,text2image,file,folder,url,sizes,check,env,update
param|?|input|URL or search term
param|?|output|output file
" -v -e '^#' -e '^\s*$'
}
#####################################################################
## Put your main script here
#####################################################################
Script:main() {
IO:log "[$script_basename] $script_version started"
Os:require curl
# shellcheck disable=SC2154
case "${action,,}" in
unsplash)
#TIP: use «splashmark unsplash» to download or search a Unsplash photo (requires free Unsplash API key)
#TIP:> splashmark unsplash "https://unsplash.com/photos/lGo_E2XonWY" rose.jpg
#TIP:> splashmark unsplash "rose" "rose.jpg"
#TIP:> splashmark unsplash rose (will generate unsplash.rose.jpg)
[[ -z "${UNSPLASH_ACCESSKEY:-}" ]] && IO:die "You need valid UNSPLASH_ACCESSKEY in .env - please copy this from https://unsplash.com/oauth/applications"
image_source="unsplash"
# shellcheck disable=SC2154
[[ -z "$input" ]] && IO:die "Need URL or search term to find an Unsplash photo"
if [[ "$input" == *"://"* ]]; then
[[ ! "$input" == *"://unsplash.com"* ]] && IO:die "[$input] is not a unsplash.com URL"
### Unsplash URL: download one photo
photo_id=$(basename "$input")
# shellcheck disable=SC2154 disable=SC2153
[[ -z "${output:-}" ]] && output="unsplash.$photo_id.$EXTENSION"
else
### search for terms
photo_id=$(unsplash:search "$input")
local photo_slug
photo_slug=$(Str:slugify "$input")
[[ -z "${output:-}" ]] && output="unsplash.$photo_slug.$EXTENSION"
fi
IO:debug "Output file: [$output]"
if [[ -n "$photo_id" ]]; then
IO:debug "Unsplash photo ID = [$photo_id]"
local image_file
image_file=$(unsplash:download "$photo_id")
unsplash:metadata "$photo_id"
Img:modify "$image_file" "$output"
IO:print "$output"
fi
;;
text2image)
#TIP: use «splashmark text2image» to create an AI generated photo (requires Replicate API key)
#TIP:> splashmark text2image "picture of a red rose" rose.jpg
#TIP:> splashmark text2image "prompt"
[[ -z "${REPLICATE_ACCESSKEY:-}" ]] && IO:die "You need valid REPLICATE_ACCESSKEY in .env - please copy this from https://replicate.com/users/pforret/account"
image_source="replicate"
# shellcheck disable=SC2154
[[ -z "$input" ]] && IO:die "Need prompt to create an AI photo"
### search for terms
local prompt_hash temp_image
prompt_hash=$(<<< "$input" Str:digest 12)
[[ -z "${output:-}" ]] && output="$image_source.$prompt_hash.$EXTENSION"
temp_image="$tmp_dir/$image_source.$prompt_hash.png"
IO:debug "Output file: [$output]"
image_file=$(ai:text2image "$input" "$temp_image")
if [[ -n "$image_file" ]]; then
Img:modify "$image_file" "$output"
IO:print "$output"
fi
;;
pixabay)
#TIP: use «splashmark pixabay» to download or search a Pixabay photo (requires free Pixabay API key)
#TIP:> splashmark pixabay "https://pixabay.com/photos/rose-flower-love-romance-beautiful-729509/" rose.jpg
#TIP:> splashmark pixabay rose rose.jpg
#TIP:> splashmark pixabay rose (will generate pixabay.rose.jpg)
[[ -z "${PIXABAY_ACCESSKEY:-}" ]] && IO:die "You need valid PIXABAY_ACCESSKEY in .env - please copy this from https://pixabay.com/api/docs/"
image_source="pixabay"
# shellcheck disable=SC2154
[[ -z "$input" ]] && IO:die "Need URL or search term to find an Pixabay photo"
if [[ "$input" == *"://"* ]]; then
[[ ! "$input" == *"://pixabay.com"* ]] && IO:die "[$input] is not a pixabay.com URL"
### Unsplash URL: download one photo
photo_id=$(basename "${input//-//}")
# shellcheck disable=SC2154
[[ -z "${output:-}" ]] && output="pixabay.$photo_id.$EXTENSION"
else
### search for terms
photo_id=$(pixabay:search "$input")
photo_slug=$(Str:slugify "$input")
[[ -z "${output:-}" ]] && output="pixabay.$photo_slug.$EXTENSION"
fi
IO:debug "Output file: [$output]"
if [[ -n "$photo_id" ]]; then
IO:debug "Pixabay photo ID = [$photo_id]"
image_file=$(pixabay:download "$photo_id")
pixabay:metadata "$photo_id"
Img:modify "$image_file" "$output"
IO:print "$output"
fi
;;
file)
#TIP: use «splashmark file» to add texts and effects to a existing image
#TIP:> splashmark file waterfall.jpg sources/original.jpg
#TIP:> splashmark --title "Strawberry" -w 1280 -c 640 -e dark,median,grain file sources/original.jpg waterfall.jpg
image_source="file"
[[ ! -f "$input" ]] && IO:die "Cannot find input file [$input]"
IO:debug "Input file : [$input]"
local name
local hash
name=$(basename "$input" .jpg | cut -c1-8)
hash=$(<<< "$input" Str:digest 6)
[[ -z "${output:-}" ]] && output="file.$name.$hash.$EXTENSION"
IO:debug "Output file: [$output]"
Img:modify "$input" "$output"
IO:print "$output"
;;
folder)
#TIP: use «splashmark folder» to add texts and effects to a existing image
#TIP:> splashmark folder /home/folder
#TIP:> splashmark --title "Strawberry" -w 1280 -c 640 -e dark,median,grain file sources/original.jpg waterfall.jpg
image_source="file"
[[ ! -d "$input" ]] && IO:die "Cannot find input folder [$input]"
IO:debug "Input folder : [$input]"
local output_folder
output_folder="$(realpath "$input")/$EXPORT"
[[ ! -d "$output_folder" ]] && mkdir -p "$output_folder"
IO:debug "Output folder : [$output_folder]"
local file base export_file
find "$input" -maxdepth 1 -type f -name "*.jpg" \
| while read -r file ; do
base=$(basename "$file" .jpg)
export_file="$output_folder/$base.$EXTENSION"
Img:modify "$file" "$export_file"
IO:print "$export_file"
done
find "$input" -maxdepth 1 -type f -name "*.png" \
| while read -r file ; do
base=$(basename "$file" .png)
export_file="$output_folder/$base.$EXTENSION"
Img:modify "$file" "$export_file"
IO:print "$export_file"
done
;;
url | u)
#TIP: use «splashmark url» to add texts and effects to a image that will be downloaded from a URL
#TIP:> splashmark file waterfall.jpg "https://i.imgur.com/rbXZcVH.jpg"
#TIP:> splashmark -w 1280 -c 640 -4 "Photographer: John Doe" -e dark,median,grain url "https://i.imgur.com/rbXZcVH.jpg" waterfall.jpg
image_source="url"
IO:debug "Download URL"
image_file=$(Img:download "$input")
[[ ! -f "$image_file" ]] && IO:die "Cannot download input image [$input]"
name=$(basename "$image_file" .jpg | cut -c1-8)
hash=$(<<< "$input" Str:digest 6)
[[ -z "${output:-}" ]] && output="url.$name.$hash.$EXTENSION"
IO:debug "Process cached image [$image_file] -> [$output]"
Img:modify "$image_file" "$output"
IO:print "$output"
;;
sizes)
Img:list_sizes \
| awk -F '|' '
{printf ("%-20s WxH: %4d x %4d\n", $1, $2, $3)}
'
;;
check | env)
## leave this default action, it will make it easier to test your script
#TIP: use «$script_prefix check» to check if this script is ready to execute and what values the options/flags are
#TIP:> $script_prefix check
#TIP: use «$script_prefix env» to generate an example .env file
#TIP:> $script_prefix env > .env
Script:check
;;
*)
IO:die "action [$action] not recognized"
;;
esac
}
#TIP: to create a social image for Github
#TIP:> splashmark -w 1280 -c 640 -z 100 -i "<user>/<repo>" -k "line 1\nline 2" -r EEEEEE -e median,dark,grain unsplash <keyword>
#TIP: to create a social image for Instagram
#TIP:> splashmark -w 1080 -c 1080 -z 150 -i "Carpe diem" -e dark pixabay clouds clouds.jpg
#TIP: to create a social image for Facebook
#TIP:> splashmark -w 1200 -c 630 -i "20 worldwide destinations\nwith the best beaches\nfor unforgettable holidays" -e dark unsplash copacabana
#####################################################################
## Put your helper scripts here
#####################################################################
### Unsplash API stuff
function unsplash:api() {
# $1 = relative API URL
# $2 = jq query path
Os:require jq
local uniq
local api_endpoint="https://api.unsplash.com"
local full_url="$api_endpoint$1"
local show_url="$api_endpoint$1"
if [[ $full_url =~ "?" ]]; then
# already has querystring
full_url="$full_url&client_id=$UNSPLASH_ACCESSKEY"
else
# no querystring yet
full_url="$full_url?client_id=$UNSPLASH_ACCESSKEY"
fi
uniq=$(echo "$full_url" | Str:digest 8)
# shellcheck disable=SC2154
local cached="$tmp_dir/unsplash.$uniq.json"
if [[ ! -f "$cached" ]]; then
# only get the data once
IO:debug "Unsplash API = [$show_url]"
curl -s "$full_url" >"$cached"
if [[ $(wc <"$cached" -c) -lt 10 ]]; then
# remove if response is too small to be a valid answer
rm "$cached"
IO:alert "API call to [$1] came back with empty response - are your Unsplash API keys OK?"
return 1
fi
if grep -q "Rate Limit Exceeded" "$cached"; then
# remove if response is API throttling starts
rm "$cached"
IO:alert "API call to [$1] was throttled - remember it's limited to 50 req/hr!"
return 2
fi
else
IO:debug "API = [$cached]"
fi
jq <"$cached" "${2:-.}" |
sed 's/"//g' |
sed 's/,$//'
}
function unsplash:metadata() {
# only get metadata if it was not yet specified as an option
[[ -z "${photographer:-}" ]] && photographer=$(unsplash:api "/photos/$1" ".user.name")
[[ -z "${url:-}" ]] && url="$(unsplash:api "/photos/$1" ".links.html")"
IO:debug "META: Photographer: $photographer"
IO:debug "META: URL: $url"
}
function unsplash:download() {
# $1 = photo_id
# returns path of downloaded file
photo_id=$(basename "/a/$1") # to avoid problems with image ID that start with '-'
image_url=$(unsplash:api "/photos/$photo_id" .urls.regular)
# shellcheck disable=SC2154
cached_image="$tmp_dir/$photo_id.jpg"
if [[ ! -f "$cached_image" ]]; then
IO:debug "IMG = [$image_url]"
curl -s -o "$cached_image" "$image_url"
else
IO:debug "IMG = [$cached_image]"
fi
[[ ! -f "$cached_image" ]] && IO:die "download [$image_url] failed"
echo "$cached_image"
}
unsplash:search() {
# $1 = keyword(s)
# returns first result
# shellcheck disable=SC2154
if [[ "$randomize" -gt 1 ]]; then
# pick random in 1st N results
choose_from=$(unsplash:api "/search/photos/?query=$1" .results[].id | wc -l)
IO:debug "PICK: $choose_from results in query"
[[ $choose_from -gt $randomize ]] && choose_from=$randomize
chosen=$((RANDOM % choose_from))
IO:debug "PICK: photo $chosen from first $choose_from results"
unsplash:api "/search/photos/?query=$1" ".results[$chosen].id"
elif [[ "$number" -gt 1 ]]; then
# take Nth result
choose_from=$(unsplash:api "/search/photos/?query=$1" .results[].id | wc -l)
IO:debug "PICK: $choose_from results in query"
[[ $choose_from -lt $number ]] && number=$choose_from
local chosen=$((number - 1))
IO:debug "PICK: photo $number from results"
unsplash:api "/search/photos/?query=$1" ".results[$chosen].id"
else
# take first photo
unsplash:api "/search/photos/?query=$1" ".results[0].id"
fi
}
### Pixabay API stuff
function pixabay:api() {
# $1 = relative API URL
# $2 = jq query path
# https://pixabay.com/api/docs/
# https://pixabay.com/api/?key={ KEY }&q=yellow+flowers&image_type=photo
Os:require jq
local uniq
local api_endpoint="https://pixabay.com/api/"
local full_url="$api_endpoint$1"
local show_url="$api_endpoint$1"
if [[ $full_url =~ "?" ]]; then
# already has querystring
full_url="$full_url&key=$PIXABAY_ACCESSKEY"
else
# no querystring yet
full_url="$full_url?key=$PIXABAY_ACCESSKEY"
fi
uniq=$(echo "$full_url" | Str:digest 8)
# shellcheck disable=SC2154
local cached="$tmp_dir/pixabay.$uniq.json"
IO:debug "API URL = [$full_url]"
IO:debug "API Cache = [$cached]"
if [[ ! -f "$cached" ]]; then
# only get the data once
IO:debug "Pixabay API = [$show_url]"
curl -s "$full_url" >"$cached"
if [[ $(wc <"$cached" -c) -lt 10 ]]; then
# remove if response is too small to be a valid answer
rm "$cached"
IO:alert "API call to [$1] came back with empty response - are your Unsplash API keys OK?"
return 1
fi
fi
jq <"$cached" "${2:-.}" |
sed 's/"//g' |
sed 's/,$//'
}
function pixabay:metadata() {
# only get metadata if it was not yet specified as an option
[[ -z "${photographer:-}" ]] && photographer=$(pixabay:api "?id=$photo_id&image_type=photo" ".hits[0].user")
[[ -z "${url:-}" ]] && url="https://pixabay.com/photos/$photo_id/"
IO:debug "META: Photographer: $photographer"
IO:debug "META: URL: $url"
}
function pixabay:download() {
# $1 = photo_id
# returns path of downloaded file
# https://pixabay.com/api/?key=<key>&id=<id>+flowers&image_type=photo
photo_id=$(basename "/a/$1") # to avoid problems with image ID that start with '-'
image_url=$(pixabay:api "?id=$photo_id&image_type=photo" .hits[0].largeImageURL)
# shellcheck disable=SC2154
cached_image="$tmp_dir/$photo_id.jpg"
if [[ ! -f "$cached_image" ]]; then
IO:debug "IMG = [$image_url]"
curl -s -o "$cached_image" "$image_url"
else
IO:debug "IMG = [$cached_image]"
fi
[[ ! -f "$cached_image" ]] && IO:die "download [$image_url] failed"
echo "$cached_image"
}
function pixabay:search() {
# $1 = keyword(s)
# returns first result
# https://pixabay.com/api/?key={ KEY }&q=yellow+flowers&image_type=photo
# shellcheck disable=SC2154
if [[ "$randomize" == 1 ]]; then
pixabay:api "?image_type=photo&q=$1" ".hits[0].id"
else
choose_from=$(pixabay:api "?image_type=photo&q=$1" .hits[].id | wc -l)
IO:debug "PICK: $choose_from results in query"
[[ $choose_from -gt $randomize ]] && choose_from=$randomize
chosen=$((RANDOM % choose_from))
IO:debug "PICK: photo $chosen from first $choose_from results"
pixabay:api "?image_type=photo&q=$1" ".hits[$chosen].id"
fi
}
### Replicate AI stuff
function ai:text2image(){
# shellcheck disable=SC2154
local status_file job_id ready url_download waits
local ai_file="$2"
[[ -f "$2" ]] && echo "$2" && return 0
status_file="$2.json"
IO:debug "Job JSON = $status_file"
if [[ ! -f $status_file ]] ; then
IO:debug "Use prompt= $1"
replicate:create "$1" > "$status_file"
else
IO:debug "Job was already started"
fi
job_id=$(< "$status_file" jq -r .id)
ready=0
waits=0
while [[ "$ready" -eq 0 ]]; do
status=$(replicate:status "$job_id" force | jq -r ".status")
if [[ "$status" == "succeeded" ]] ; then
ready=1
else
waits=$((waits + 1))
[[ "$waits" -gt 100 ]] && return 1
printf "."
IO:debug "waiting 10 seconds ..."
sleep 10
fi
done
printf "\r"
url_download=$(replicate:status "$job_id" | jq -r ".output[0]")
IO:debug "Download: $url_download"
IO:debug "AI Image: $ai_file"
curl -s -o "$ai_file" "$url_download"
echo "$ai_file"
}
function replicate:create() {
# cf: https://replicate.com/stability-ai/stable-diffusion/api
local endpoint="https://api.replicate.com/v1/predictions"
local prompt="$1"
curl -s \
-H "Authorization: Token $REPLICATE_ACCESSKEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "{ \"version\": \"db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf\", \"input\": { \"prompt\": \"$prompt\" } } " \
"$endpoint" | jq
}
function replicate:status(){
local job_id="$1"
local status_file="$tmp_dir/$1.json"
if [[ -f "$status_file" ]] ; then
if [[ ! "${2:-}" == "force" ]] ; then
cat "$status_file"
return 0
fi
fi
IO:debug "Update job status in $status_file"
curl -s \
-H "Authorization: Token $REPLICATE_ACCESSKEY" \
-H 'Content-Type: application/json' \
"https://api.replicate.com/v1/predictions/$job_id" \
| tee "$status_file"
}
### Image URL stuff
function Img:download() {
# $1 = url
local uniq
local extension="jpg"
[[ "$1" =~ .png ]] && extension="png"
[[ "$1" =~ .gif ]] && extension="gif"
uniq=$(echo "$1" | Str:digest 8)
# shellcheck disable=SC2154
local cached_image="$tmp_dir/download.$uniq.$extension"
if [[ ! -f "$cached_image" ]]; then
IO:debug "IMG = [$1]"
curl -s -o "$cached_image" "$1"
else
IO:debug "IMG = [$cached_image]"
fi
echo "$cached_image"
}
### Modify images
function Img:exif() {
local filename="$1"
local exif_key="$2"
local exif_val="$3"
if [[ -n "$exif_val" ]]; then
IO:debug "EXIF: set [$exif_key] to [$exif_val] for [$filename]"
exiftool -overwrite_original -"$exif_key"="$exif_val" "$filename" >/dev/null 2>/dev/null
fi
}
function Img:metadata() {
Os:require exiftool
# $1 = type
# $2 = filename
# https://exiftool.org/TagNames/index.html
# Artist : Artist
# By-line : Author
# By-line Title : Author Title
# Caption-Abstract : Caption
# Category : Category
# City : City
# Copyright Notice : Copyright
# Country-Primary Location Name : Country
# Creator : Creator
# Credit : Credit
# Headline : Headline
# ImageDescription : ImageDescription
# Keywords : Keywords
# Object Name : Document Title
# Owner Name : OwnerName
# Source : Source
# Special Instructions : Instructions
# Sub-location : Sub-location
# Supplemental Categories : OtherCategories
# Urgency : 1 (most urgent)
# Writer-Editor : Caption Writer
Img:exif "$2" "Writer-Editor" "pforret/splashmark"
if [[ "$1" == "unsplash" ]]; then
## metadata comes from Unsplash/Pixabay
if [[ -f "$2" && -n ${photographer} ]]; then
Img:exif "$2" "Artist" "$photographer"
Img:exif "$2" "Creator" "$photographer"
Img:exif "$2" "OwnerID" "$photographer"
Img:exif "$2" "OwnerName" "$photographer"
Img:exif "$2" "Credit" "Photo: $photographer on Unsplash.com"
Img:exif "$2" "ImageDescription" "Photo: $photographer on Unsplash.com"
fi
else
## metadata, if any, comes from command line options
if [[ -f "$2" && -n ${photographer} ]]; then
Img:exif "$2" "Artist" "$photographer"
Img:exif "$2" "Creator" "$photographer"
Img:exif "$2" "OwnerID" "$photographer"
Img:exif "$2" "OwnerName" "$photographer"
Img:exif "$2" "ImageDescription" "Photo: $photographer"
fi
fi
}
function Img:modify() {
# $1 = input file
# $2 = output file
Os:require convert imagemagick
local font_list
# shellcheck disable=SC2154
font_list="$tmp_dir/magick.fonts.txt"
if [[ ! -f "$font_list" ]]; then
convert -list font | awk -F: '/Font/ {gsub(" ","",$2); print $2 }' >"$font_list"
fi
if [[ -f "$fonttype" ]]; then
IO:debug "FONT [$fonttype] exists as a font file"
elif grep -q "$fonttype" "$font_list"; then
IO:debug "FONT [$fonttype] exists as a standard font"
elif [[ -f "$script_install_folder/fonts/$fonttype" ]]; then
fonttype="$script_install_folder/fonts/$fonttype"
IO:debug "FONT [$fonttype] exists as a splashmark font"
else
IO:die "FONT [$fonttype] cannot be found on this system"
fi
[[ ! -f "$1" ]] && return 1
## scale and crop
# shellcheck disable=SC2154
if [[ -n "$preset" ]] ; then
if [[ $(Img:list_sizes | grep -c "$preset") == 1 ]] ; then
width="$(Img:list_sizes | grep "$preset" | cut -d'|' -f2)"
crop="$(Img:list_sizes | grep "$preset" | cut -d'|' -f3)"
IO:debug "Dimensions are now: $width x $crop ($preset)"
fi
# shellcheck disable=SC2154
if [[ -n "$resize" ]] ; then
width=$(Tool:calc "$width * $resize")
crop=$(Tool:calc "$crop * $resize")
IO:debug "Dimensions are now: $width x $crop (resize x$resize)"
fi
fi
# shellcheck disable=SC2154
if [[ "$crop" -gt 0 ]]; then
IO:debug "CROP: image to $width x $crop --> $2"
convert "$1" -gravity Center -resize "${width}x${crop}^" -crop "${width}x${crop}+0+0" +repage -quality 95% "$2"
else
IO:debug "SIZE: to $width wide --> $2"
convert "$1" -gravity Center -resize "${width}"x -quality 95% "$2"
fi
## set EXIF/IPTC tags
IO:debug "Img:metadata"
Img:metadata "$image_source" "$2"
## do visual effects
# shellcheck disable=SC2154
if [[ -n "$effect" ]]; then
IO:debug "Img:effect"
# shellcheck disable=SC2154
Img:effect "$2" "$effect"
fi
## add small watermarks in the corners
# shellcheck disable=SC2154
[[ -n "$northwest" ]] && Img:watermark "$2" NorthWest "$northwest"
# shellcheck disable=SC2154
[[ -n "$northeast" ]] && Img:watermark "$2" NorthEast "$northeast"
# shellcheck disable=SC2154
[[ -n "$southwest" ]] && Img:watermark "$2" SouthWest "$southwest"
# shellcheck disable=SC2154
[[ -n "$southeast" ]] && Img:watermark "$2" SouthEast "$southeast"
## add large title watermarks in the middle
# shellcheck disable=SC2154
[[ -n "$title" || -n "$subtitle" ]] && Img:title "$2"
}
function text_resolve() {
case $image_source in
unsplash)
echo "$1" |
sed "s|{copyright}|Photo by {photographer} on Unsplash.com|" |
sed "s|{copyright2}|© {photographer} » Unsplash.com|" |
sed "s|{photographer}|$photographer|" |
sed "s|{url}|$url|" |
sed "s|https://||"
;;
pixabay)
echo "$1" |
sed "s|{copyright}|Photo by {photographer} on Pixabay.com|" |
sed "s|{copyright2}|© {photographer} » Pixabay.com|" |
sed "s|{photographer}|$photographer|" |
sed "s|{url}|$url|" |
sed "s|https://||"
;;
*)
echo "$1" |
sed "s|{copyright}| |" |
sed "s|{copyright2}| |" |
sed "s|{photographer}| |" |
sed "s|{url}| |" |
sed "s|https://||"
;;
esac
}
function rescale_weight(){
local percent="$1"
local percent0="$2"
local percent100="$3"
local rescaled
if [[ "${4:-int}" == "float" ]] ; then
rescaled=$(awk "BEGIN {print $percent0 + ( $percent100 - $percent0 ) * $percent / 100 }")
else
rescaled=$(( percent0 + ( percent100 - percent0 ) * percent / 100 ))
fi
IO:debug "Rescaled: $percent => $rescaled"
echo "$rescaled"
}
function Img:effect() {
# $1 = image path
# $2 = effect name
# shellcheck disable=SC2154
[[ ! -f "$1" ]] && return 1
Os:require mogrify imagemagick
local weight
local shrink
local percent
local large
local expand
# shellcheck disable=SC2154
for fx1 in $(echo "$2" | tr ',' "\n"); do
IO:debug "Effect : $fx1"
# shellcheck disable=SC2001
percent="$(echo "$fx1" | sed 's/[^0-9]//g')"
percent="${percent:-20}"
IO:debug "Weight : $percent %"
case "$fx1" in
blur*) weight=$(rescale_weight "$percent" 0 50); mogrify -blur "${weight:-5}x${weight:-5}" "$1" ;;
bw) mogrify -modulate 100,0,100 "$1" ;;
dark*) weight=$(rescale_weight "$percent" 0 100); mogrify -fill black -colorize "${weight}%" "$1" ;;
desat*) weight=$(rescale_weight "$percent" 100 0); mogrify -modulate "100,$weight,100" "$1" ;;
grain*) weight=$(rescale_weight "$percent" 0 2 float); mogrify -attenuate "${weight}" +noise Gaussian "$1" ;;
light*) weight=$(rescale_weight "$percent" 0 100); mogrify -fill white -colorize "${weight}%" "$1" ;;
median*) weight=$(rescale_weight "$percent" 0 10); mogrify -median "${weight}" "$1" ;;
monochrome) mogrify -modulate 100,0,100 "$1" ;;
noise*) weight=$(rescale_weight "$percent" 0 2 float); mogrify -attenuate "${weight}" +noise Gaussian "$1" ;;
norm) mogrify -normalize "$1" ;;
normalize) mogrify -normalize "$1" ;;
paint*) weight=$(rescale_weight "$percent" 0 10); mogrify -paint "${weight}" "$1" ;;
pixel*) shrink=$(awk "BEGIN {print int(250/$percent) }"); expand=$(awk "BEGIN {print int(10000/$shrink) }"); mogrify -resize "${shrink}%" -scale "${expand}%" "$1" ;;
sketch*) weight=$(rescale_weight "$percent" 0 10); mogrify -sketch "${weight}x${weight}+45" "$1" ;;
vignette*) weight=$(rescale_weight "$percent" 200 20); large=$(rescale_weight "$percent" 100 0); mogrify -background black -vignette "0x${weight}-${large}-${large}" "$1" ;;
*)
# shellcheck disable=SC2086
eval mogrify $effect "$1"
;;
esac
done
}
function Img:watermark() {
# $1 = image path
# $2 = gravity
# $3 = text
[[ ! -f "$1" ]] && return 1
Os:require mogrify imagemagick
IO:debug "Img:watermark $3"
# shellcheck disable=SC2154
char1=$(Str:upper "${fontcolor:0:1}")
case $char1 in
9 | A | B | C | D | E | F)
shadow_color="0008"
;;
*)
shadow_color="FFF8"
;;
esac
text=$(text_resolve "$3")
IO:debug "MARK: [$text] in $2 corner ..."
# shellcheck disable=SC2154
local margin2=$((margin + 1))
# shellcheck disable=SC2154
mogrify -gravity "$2" -font "$fonttype" -pointsize "$fontsize" -fill "#$shadow_color" -annotate "0x0+${margin2}+${margin2}" "$text" "$1"
mogrify -gravity "$2" -font "$fonttype" -pointsize "$fontsize" -fill "#$fontcolor" -annotate "0x0+${margin}+${margin}" "$text" "$1"
}
function choose_position() {
position="$1"
# shellcheck disable=SC2154
case ${gravity,,} in
left | west) position="${position}West" ;;
right | east) position="${position}East" ;;
esac
[[ -z "$position" ]] && position="Center"
echo "$position"
}
function Img:title() {
# $1 = image path
[[ ! -f "$1" ]] && return 1
# shellcheck disable=SC2154
char1=$(Str:upper "${fontcolor:0:1}")
case $char1 in
9 | A | B | C | D | E | F)
shadow_color="0008"
;;
*)
shadow_color="FFF8"
;;
esac
# shellcheck disable=SC2154
local margin1=$((margin * 3))
local margin2=$((margin1 + 1))
if [[ -n "$title" ]]; then
text=$(text_resolve "$title")
position=""
[[ -n "$subtitle" ]] && position="North"
position=$(choose_position "$position")
IO:debug "MARK: title [$text] in $position ..."
# shellcheck disable=SC2154
if [[ $(Str:lower "$gravity") == "center" ]]; then
mogrify -gravity "$position" -font "$fonttype" -pointsize "$titlesize" -fill "#$shadow_color" -annotate "0x0+1+${margin2}" "$text" "$1"
mogrify -gravity "$position" -font "$fonttype" -pointsize "$titlesize" -fill "#$fontcolor" -annotate "0x0+0+${margin1}" "$text" "$1"
else
mogrify -gravity "$position" -font "$fonttype" -pointsize "$titlesize" -fill "#$shadow_color" -annotate "0x0+${margin2}+${margin2}" "$text" "$1"
mogrify -gravity "$position" -font "$fonttype" -pointsize "$titlesize" -fill "#$fontcolor" -annotate "0x0+${margin1}+${margin1}" "$text" "$1"
fi
fi
if [[ -n "$subtitle" ]]; then
text=$(text_resolve "$subtitle")
position=""
[[ -n "$title" ]] && position="South"
position=$(choose_position "$position")
IO:debug "MARK: subtitle [$text] in $position ..."
# shellcheck disable=SC2154
if [[ $(Str:lower "$gravity") == "center" ]]; then
mogrify -gravity "$position" -font "$fonttype" -pointsize "$subtitlesize" -fill "#$shadow_color" -annotate "0x0+1+${margin2}" "$text" "$1"
mogrify -gravity "$position" -font "$fonttype" -pointsize "$subtitlesize" -fill "#$fontcolor" -annotate "0x0+0+${margin1}" "$text" "$1"
else
mogrify -gravity "$position" -font "$fonttype" -pointsize "$subtitlesize" -fill "#$shadow_color" -annotate "0x0+${margin2}+${margin2}" "$text" "$1"
mogrify -gravity "$position" -font "$fonttype" -pointsize "$subtitlesize" -fill "#$fontcolor" -annotate "0x0+${margin1}+${margin1}" "$text" "$1"
fi
fi
}
function Img:list_sizes(){
cat <<END
cinema:flat|1998|1080
cinema:hd|1920|1080
cinema:scope|2048|858
facebook:cover|851|315
facebook:horizontal|1200|630
facebook:story|1080|1920
facebook:vertical|1080|1350
github:repo|1280|640
instagram:horizontal|1350|1080
instagram:square|1080|1080
instagram:story|1080|1920
instagram:vertical|1080|1350
linkedin:horizontal|1104|736
medium:horizontal|1500|1200
pinterest:vertical|1000|1500
tumblr:vertical|1280|1920
twitter:header|1500|500
twitter:post|1024|512
END
}
#####################################################################
################### DO NOT MODIFY BELOW THIS LINE ###################
#####################################################################
# set strict mode - via http://redsymbol.net/articles/unofficial-bash-strict-mode/
# removed -e because it made basic [[ testing ]] difficult
set -uo pipefail
IFS=$'\n\t'
force=0
help=0
error_prefix=""
#to enable verbose even before option parsing
verbose=0
[[ $# -gt 0 ]] && [[ $1 == "-v" ]] && verbose=1
#to enable quiet even before option parsing
quiet=0
[[ $# -gt 0 ]] && [[ $1 == "-q" ]] && quiet=1
### stdIO:print/stderr output
function IO:initialize() {
[[ "${BASH_SOURCE[0]:-}" != "${0}" ]] && sourced=1 || sourced=0
[[ -t 1 ]] && piped=0 || piped=1 # detect if output is piped
[[ -z "${TERM:-}" ]] && TERM=xterm
if [[ $piped -eq 0 ]]; then
txtReset=$(tput sgr0)
txtError=$(tput setaf 160)
txtInfo=$(tput setaf 2)
txtWarn=$(tput setaf 214)
txtBold=$(tput bold)
txtItalic=$(tput sitm)
txtUnderline=$(tput smul)
else
txtReset=""
txtError=""
txtInfo=""
txtInfo=""
txtWarn=""
txtBold=""
txtItalic=""
txtUnderline=""
fi
[[ $(echo -e '\xe2\x82\xac') == '€' ]] && unicode=1 || unicode=0 # detect if unicode is supported
if [[ $unicode -gt 0 ]]; then
char_succes="✅"
char_fail="⛔"
char_alert="✴️"
char_wait="⏳"
info_icon="🌼"
config_icon="🌱"
clean_icon="🧽"
require_icon="🔌"
else
char_succes="OK "
char_fail="!! "
char_alert="?? "
char_wait="..."
info_icon="(i)"
config_icon="[c]"
clean_icon="[c]"
require_icon="[r]"
fi
error_prefix="${txtError}>${txtReset}"
}
function IO:print() {
((quiet)) && true || printf '%b\n' "$*"
}
function IO:debug() {
((verbose)) && IO:print "${txtInfo}# $* ${txtReset}" >&2
true
}
function IO:die() {
IO:print "${txtError}${char_fail} $script_basename${txtReset}: $*" >&2
Os:beep fatal
Script:exit
}
function IO:alert() {
IO:print "${txtWarn}${char_alert}${txtReset}: ${txtUnderline}$*${txtReset}" >&2
}
function IO:success() {
IO:print "${txtInfo}${char_succes}${txtReset} ${txtBold}$*${txtReset}"
}
function IO:announce() {
IO:print "${txtInfo}${char_wait}${txtReset} ${txtItalic}$*${txtReset}"
sleep 1
}
function IO:progress() {
((quiet)) || (
local screen_width
screen_width=$(tput cols 2>/dev/null || echo 80)
local rest_of_line
rest_of_line=$((screen_width - 5))
if ((piped)); then
IO:print "... $*" >&2
else
printf "... %-${rest_of_line}b\r" "$* " >&2
fi
)
}
### interactive
function IO:confirm() {
((force)) && return 0
read -r -p "$1 [y/N] " -n 1
echo " "
[[ $REPLY =~ ^[Yy]$ ]]
}
function IO:question() {
local ANSWER
local DEFAULT=${2:-}
read -r -p "$1 ($DEFAULT) > " ANSWER
[[ -z "$ANSWER" ]] && echo "$DEFAULT" || echo "$ANSWER"
}
function IO:log() {
[[ -n "${log_file:-}" ]] && echo "$(date '+%H:%M:%S') | $*" >>"$log_file"
}
function Tool:calc() {
awk "BEGIN {print $*} ; "
}
function Tool:time() {
if [[ $(command -v perl) ]]; then
perl -MTime::HiRes=time -e 'printf "%.3f\n", time'
elif [[ $(command -v php) ]]; then
php -r 'echo microtime(true) . "\n"; '
elif [[ $(command -v python) ]]; then
python -c "import time; print(time.time()) "
else
date "+%s" | awk '{printf("%.3f\n",$1)}'
fi
}
### string processing
function Str:trim() {
local var="$*"
# remove leading whitespace characters
var="${var#"${var%%[![:space:]]*}"}"
# remove trailing whitespace characters
var="${var%"${var##*[![:space:]]}"}"
printf '%s' "$var"
}
function Str:lower() {
if [[ -n "$1" ]]; then
local input="$*"
echo "${input,,}"
else