Skip to content

Instantly share code, notes, and snippets.

@jooray
Last active May 6, 2019 05:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jooray/ed1fefc491612dac2055f0f8a649650c to your computer and use it in GitHub Desktop.
Save jooray/ed1fefc491612dac2055f0f8a649650c to your computer and use it in GitHub Desktop.
vCard photo extractor
#!/bin/bash
# originally from
# https://raw.githubusercontent.com/mattbrock/mattbrock/master/vCard_photo_extractor/vCard_photo_extractor.sh
# changes:
# - made to work with macOS's base64 (uses -D not -d)
# - does not convert to fixed resolution
# - uses identify to remove invalid images
# - handles special characters better
progname=$(basename $0)
usage="Usage:\t$progname -f vCard_file \n\t$progname -h"
while getopts "f:h" options ; do
case $options in
f) vcard_file=$OPTARG ;;
h) echo -e $usage ; exit ;;
esac
done
if [ ! "$vcard_file" ] ; then
echo -e $usage
exit 1
fi
if [[ ! $(head -1 $vcard_file) =~ "BEGIN:VCARD" ]] ; then
echo "$vcard_file does not appear to be a vCard file"
exit 1
fi
if ! which base64 > /dev/null ; then
echo "base64 is not installed"
exit 1
fi
if ! which identify > /dev/null ; then
echo "ImageMagick is not installed"
echo "Either install it or comment out the ImageMagick stuff"
exit 1
fi
if [ -d photos ] ; then
echo "photos directory already exists"
exit 1
fi
if ! mkdir photos ; then
echo "Failed to create photos directory"
exit 1
fi
regex1="^N:"
regex2="^PHOTO;"
regex3=":|;"
echo -ne "Extracting photos"
cat $vcard_file | while read line ; do
if [[ $line =~ $regex1 ]] ; then
filename=$(echo $line | awk -F '[:;]' '{printf("%s%s",$3,$2)}' |
iconv -c -f UTF-8 -t ASCII//TRANSLIT | sed 's/[^a-zA-Z]//g')
echo -ne "."
cat /dev/null > photos/$filename.tmp
elif [[ $line =~ $regex2 ]] ; then
echo $line | sed 's/PHOTO;ENCODING=b;TYPE=JPEG://' >> photos/$filename.tmp
elif [[ ! $line =~ $regex3 ]] ; then
echo $line >> photos/$filename.tmp
fi
done
echo -ne " done\n"
echo -ne "Removing empty photos..."
find photos -empty -exec rm -f {} +
echo -ne " done\n"
echo -ne "Cleaning up photos"
cd photos
for file in *.tmp ; do
filename=${file%.tmp}
echo -ne "."
cat $file | tr -d '\n' | tr -d '
' | base64 -D > $filename.jpg
rm -f $file
identify -format '%f' $filename.jpg >/dev/null 2>&1 || {
echo && echo "Error: $filename.jpg is not a valid image file, deleting"
rm -f $filename.jpg
}
done
echo -ne " done\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment