Last active
January 8, 2021 22:41
-
-
Save priteshgohil/841d972381984047c32c556892060bf6 to your computer and use it in GitHub Desktop.
Convert all images in directory to pdf file and produce compressed pdf file using ghostscript. Most suitable for image compression without loosing much of information.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#title :images2pdf.sh | |
#description :Best image compression ever. | |
#author :Pritesh Gohil | |
#date :08 Jan 2021 | |
#version :0.1 | |
#usage :bash images2pdf.sh -i ../Desktop/img_dir/ | |
#notes :Install ImageMagick and ghostscript packages. | |
#bash_version :5.0.16(1)-release | |
#============================================================================== | |
HELP=" | |
Convert images in the src_dir to low resolution pdf files using ImageMagick and GhostScript | |
[-h] Help | |
[-i <image_directory>] Image directory | |
[-o <save_directory>] Path to save results (TO DO: NOT IMPLEMENTED) | |
[-c] Compress original pdf (TO DO: NOT IMPLEMENTED) | |
" | |
# Get arguments | |
options="i:o:h?" | |
while getopts $options opt; do | |
case "$opt" in | |
h) | |
echo "$HELP" | |
exit 0 | |
;; | |
i) src_dir=$OPTARG | |
;; | |
o) out_dir=$OPTARG | |
;; | |
esac | |
done | |
# Check atleast one argument given | |
if ((OPTIND==1)) | |
then | |
echo "Please provide input source directory. Use -i <src_dir>" | |
exit 0 | |
fi | |
echo Arguments: $@ | |
if [ -z $src_dir ] #If -i args not provided | |
then | |
echo "No such source directory" | |
exit 0 | |
else | |
if [ ! -d "$src_dir" ]; #if directory doesn't exist | |
then | |
echo "invalid directory!!!" | |
exit 0 | |
fi | |
echo "reading images" | |
# find "$src_dir" -type f -regex ".*\.\(png\|jpg\|jpeg\)" -print0 | while IFS= read -r -d $'\0' in_file | |
# for file in "$src_dir"*.{jpg,jpeg,png} ; | |
for file in $(ls $src_dir*.jpg $src_dir*.jpeg $src_dir*.png); | |
do | |
echo "converting file $file" | |
IMG=${file%.*}".pdf" #Remove file extension | |
convert "$file" "$IMG.pdf" #Intentinal double extension | |
# Reduce pdf size using ghostscript | |
echo "Compressing pdf" | |
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.5 -dNOPAUSE -dQUIET -dBATCH -dPrinted=false -sOutputFile=$IMG $IMG".pdf" | |
# Remove double extension extra files | |
rm $IMG".pdf" | |
done | |
fi | |
echo "finished conversion" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment