Help:Command line image processing with ImageMagick

From Biowikifarm Metawiki
Jump to: navigation, search

Create GIF animation from multiple files (myfile01.jpg, myfile02.jpg, ...) on the fly with Linux

Suppose you have several files (myfile01.jpg, myfile02.jpg, ...) and you want them converted into a file “animation.gif”. The following script will do it on the fly using convert (ImageMagick):

1 echo   myfile*.jpg | \
2   sed '1 s/^/echo "Start "`date`"..." \&\& convert /
3          s/$/ \\/
4        $ s/\\$/animation.gif \&\&  echo "Done  "`date`/' \
5 | sh

The trick behind this is to put things together by the “|” character (piping). The “\”-character continues the shell-command when there are line breaks and “&&” joins shell commands together. Explanations for each line in the script:

  1. gets all files (file01.jpg, file02.jpg, ...). To get those numbered files see man rename.
  2. sed composes and extends the piped echo. Prepend at the sed-address “the very first line” (1 s/../../) and do a regular expression replace by «s/search/replace/». So «1 s/^/.../» puts something at the 1st line but at the beginning of this line (^) and prepends therefore «echo "Start "`date`"..." && convert »
  3. at each single line end ($) put a “ \”-character to get multi line echoed files into one single command
  4. append at the sed-address “the very last line” ($ s/../../), search here for “\”-at the very end of the current line ($) and replace it by «animation.gif && echo "Done "`date`»
  5. pipe all this together to the shell, which may something like:
echo "Start "`date`"..." && convert myfile01.jpg myfile02.jpg myfile03.jpg test.gif &&  echo "Done  "`date`

BTW: You can test the echoed command first by deleting the last pipe “| sh”.

Usually you can do the same by just typing:

convert myfile*.jpg animation.gif

...but if files have different dates or if they where saved at different times, this can cause a distorted animation. So the safe way is to explicitly let convert use only the provided file order.