Skip to content

Instantly share code, notes, and snippets.

@dmaglio
Forked from unot/zip2cbz.sh
Last active November 15, 2017 15:46
Show Gist options
  • Save dmaglio/bc680177fc8b4f9799f749c8c2816024 to your computer and use it in GitHub Desktop.
Save dmaglio/bc680177fc8b4f9799f749c8c2816024 to your computer and use it in GitHub Desktop.
Zipped jpeg files to CBZ file for Kobo Glo.
#!/bin/bash -ex
# zip2cbz.sh
# Written by Takashi UNO
# require: zip, ImageMagick
# if [ $# -ne 1 ]; then
# echo "USAGE: $(basename $0) hogehoge.zip"
# exit 1
# fi
OPTIPNGOPTIONS="-quiet"
SIZE="1072x1448"
CWD="$(pwd)"
for cmd in zip unzip convert; do
if [ ! -x "$(which $cmd)" ]; then
echo "command $cmd is not found."
exit 1
fi
done
if [ ! -f "$1" ]; then
echo "$1: file not exist."
exit 1
fi
file=$1
if [[ "$file" =~ \ |\' ]]; then
newname=${file//[^0-9A-Za-z_.]/_}
echo "newname $newname"
if [ ! -e "$newname" ]; then
cp "$file" "$newname"
fi
file=$newname
fi
echo "file: $file"
if [[ ${file: -3} == "zip" ]]; then
TMPDIR="$CWD/$(basename "$file" .zip)"
elif [[ ${file: -3} == "rar" ]]; then
TMPDIR="$CWD/$(basename "$file" .rar)"
fi
echo "tmpdir ${TMPDIR}"
#trap 'rm -rf "${TMPDIR}"' EXIT
mkdir -p "${TMPDIR}/unzip"
mkdir "${TMPDIR}/png"
if [[ ${file: -3} == "zip" ]]; then
unzip -q "$file" -d "${TMPDIR}/unzip"
elif [[ ${file: -3} == "rar" ]]; then
unrar x "$file" "${TMPDIR}/unzip"
fi
pushd "${TMPDIR}/unzip" >/dev/null
SAVEIFS=IFS
IFS=$(echo -en "\n\b")
array=($(find . -depth -type d)) # Find catalogs recursively.
pattern=" |'"
for i in "${array[@]}"; do
pushd "$i" >/dev/null 2>&1
for name in *; do
if [[ "$name" =~ $pattern ]]; then
newname_inside=${name//[^0-9A-Za-z_.]/_}
if [ ! -e "$newname_inside" ]; then
mv "$name" "$newname_inside"
fi
fi
done
popd >/dev/null 2>&1
done
IFS=$SAVEIFS
SAVEIFS=IFS
IFS=$(echo -en "\n\b")
array=($(find . -type d -printf "%P\n")) # Find catalogs recursively.
for i in "${array[@]}"; do
mkdir -p "${TMPDIR}/png/$i"
done
IFS=$SAVEIFS
# if [ ! -x "$(which parallel)" ]; then
find . -name "*.jpg" -printf "%P\n" | while read -r src; do
echo "$src"
convert "$src" -type grayscale -fuzz 50% png:- | convert - -depth 4 -resize $SIZE "${TMPDIR}/png/${src%.jpg}.png" && optipng ${OPTIPNGOPTIONS} "${TMPDIR}/png/${src%.jpg}.png"
done
# else
# find . -name "*.jpg" -printf "%P\n" | while read -r src; do
# echo "$src"
# parallel -j4 "convert $src -type grayscale -fuzz 50% png:- | convert - -depth 4 -resize $SIZE ${TMPDIR}/png/${src%.jpg}.png && optipng ${OPTIPNGOPTIONS} ${TMPDIR}/png/${src%.jpg}.png"
# done
# fi
popd >/dev/null
zip -qr "${file%.zip}.cbz" "${TMPDIR}/png"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment