|
#!/bin/bash
# extract_frames_from_animated_gif: Extracts frames from an animated GIF :)
# This program writes each extracted frame to its own file in /tmp, then creates
# simple HTML file that shows each individual frame.
# BUUS: This script is part of Brian's Useful Utilities Set
function die {
echo "extract_frames_from_animated_gif: $1" >&2
exit 1
}
# Some preliminary checks
[ -z "$1" ] && die "require the name of an image file"
[ -f "$1" ] || die "$1: not found"
[ -r "$1" ] || die "$1: can't read"
# Does the file contain an image?
file "$1" | grep -q image || die "$1: file does not contain an image"
# Determine how many frames there are in the GIF
SCENES=$(identify -format %n $1)
[ $SCENES -lt 2 ] && die "$1: contains only one image"
# Get the basename for the extracted images
X="$(basename "$1" | tr '[A-Z]' '[a-z]')"
BASENAME="${X%.gif}"
[ "$X" = "$BASENAME" ] && BASENAME="${X%.png}"
# Extract the images
rm -f /tmp/*.frame.gif >/dev/null 2>&1
NUMBER_WIDTH=${#SCENES}
convert "$1[0-$SCENES]" /tmp/${BASENAME}_%0${NUMBER_WIDTH}d.frame.gif
# Build an HTML file with the image sequences
WIDTH=$(identify -format "%w\n" "$1"|head -n 1)
WIDTH=$((WIDTH+4))
COLUMNS=$((1000/$WIDTH))
HTML_FN="/tmp/$BASENAME.html"
cat - <<EOF1 >"$HTML_FN"
<html>
<head>
<title>$1 - $SCENES frames</title>
</head>
<body>
<h1>$1</h1>
<table border="1" cellspacing="0" cell[adding="1">
EOF1
FRAME_NUM=0
ROW_NUM=0
COL_NUM=$((COLUMNS+1))
for FRAME_FN in /tmp/*.frame.gif
do
if [ $COL_NUM -ge $COLUMNS ]
then
[ $ROW_NUM -gt 0 ] && echo -e "\t</tr>" >>"$HTML_FN"
ROW_NUM=$((ROW_NUM+1))
COL_NUM=0
echo -e "\t<tr>" >>"$HTML_FN"
fi
FRAME_NUM=$((FRAME_NUM+1))
COL_NUM=$((COL_NUM+1))
echo -e "\t\t<td><img src='$FRAME_FN' title='frame $FRAME_NUM' alt='frame $FRAME_NUM' />" >>$HTML_FN
done
# Close off the last row
if [ $COL_NUM -lt $COLUMNS ]
then
echo -e "\t\t<td colspan='$((COLUMNS-$COL_NUM))' align='center'>End</td>" >>$HTML_FN
fi
# Close off the file
cat - <<EOF2 >>$HTML_FN
</tr>
</table>
</body>
EOF2
echo "Wrote $SCENES frames to $HTML_FN"
# vim: tabstop=4
|