Linux jpg to gif

How do I create an animated gif from still images (preferably with the command line)?

I want make a .gif animated picture from a given set of .jpg pictures. I would prefer to do it from the command line, so command line tools would be very welcome.

7 Answers 7

You can use ImageMagick package. Install it using the command:

sudo apt-get install imagemagick 

Now you can create a gif from number of pictures( jpg ) using:

convert -delay 20 -loop 0 *.jpg myimage.gif 

ImageMagick users will likely also want: -deconstruct . I have also found that ImageMagick is very memory hungry, see benchmarks: askubuntu.com/a/1102183/52975

To complete @Maythux answer:

To avoid generating a very large file, you can use -resize option:

In my case, I have 4608×3456 images and the generated gif was more than 300M for 32 images

convert -resize 20% -delay 20 -loop 0 *.jpg myimage.gif 
convert -resize 768x576 -delay 20 -loop 0 *.jpg myimage.gif 

Take care of *.jpg

*.jpg sucks a bit when dealing with numeric values, you may generate a gif with unsorted pics.

$ ls|cat 21-33-26_1.jpg 21-33-26_10.jpg //  

As the shots were taken very quickly (10/s) they all have the same modification time and you can't trick using ls -t for example. On ubuntu you can use ls -v instead, something like:

convert -resize 768x576 -delay 20 -loop 0 `ls -v` myimage.gif 

Sorting numerically is quite tricky on Mac OS X though, I guess you'll need to build a custom script.

You can avoid your *.jpg issue by forward padding numbers with zeros. "01.jpg" instead of "1.jpg", and so on. If you get to triple digits, then "001.jpg", "010.jpg", etc.

There are several ways around the filename sequence problem. Including find , sort , brace expansion, and so on. The ls tool is notoriously unsuitable for this kind of thing. Use find . There's a bit of a learning curve, but it's worth it.

If the input has a transparent background, I would also recommend the -dispose Background option. (I realize OP's post is about jpeg images which cannot have transparent backgrounds, but just in case anyone finds this answer via Google, like I did). By the way, regarding the ls sorting, you could always do some bash script hacking inline, e.g.: $(for f in `seq 0 10`; do printf "21-33-26_$f.jpg\n"; done)

ffmeg solution + test data

As of Ubuntu 18.10, ffpmeg 4.0.2-2, ImageMagick 6.9.10-8, I have found that ffmpeg is much faster than ImageMagick, and uses much less memory.

The simplest conversion command is:

ffmpeg \ -framerate 60 \ -pattern_type glob \ -i '*.png' \ -r 15 \ -vf scale=512:-1 \ out.gif \ ; 

You can get my test data with:

wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true unzip opengl-rotating-triangle.zip cd opengl-rotating-triangle 

The important ffmpeg options I want to highlight are:

  • -pattern_type glob : convenient way to select images
  • -framerate 60 : assume 60 FPS on input images, and output the same FPS. ffmpeg cannot know otherwise, since there is no FPS data is in images as there is is in video formats. The 256 input frames take about 4 seconds to finish. -r 15 : optional. Pick one every 4 images so reduce size ( 4 == 60 / 15 ). With it, identify out.gif says that the GIF contains only 64 frames. It still takes 4 seconds to play, so the delay is altered to make things match.
  • -vf scale=512:-1 : optional. Set the width, scale height proportionally, usually to reduce size and save space.

ImageMagick vs ffmpeg benchmark

To get ImageMagick to work, I first had to modify its disk and memory limits at /etc/ImageMagick-6/policy.xml as explained at: https://superuser.com/questions/1178666/imagemagick-convert-quits-after-some-pages

/usr/bin/time -v convert *.png -deconstruct -delay 1.6 out-convert.gif /usr/bin/time -v ffmpeg \ -framerate 60 \ -pattern_type glob \ -i '*.png' \ out-ffmpeg.gif \ ; 

The commands were constructed to produce outputs that are as close as possible to make the comparison valid:

  • /usr/bin/time -v : used to find the maximum memory usage as explained at: https://stackoverflow.com/questions/774556/peak-memory-usage-of-a-linux-unix-process
  • -deconstruct : GIF images can contain just the minimal modified rectangle from the previous frame to make the GIF smaller. ffmpeg calculates those diffs by default, but ImageMagick does not, unless -deconstruct is used. You will basically want to use that option every time with ImageMagick. We can observe the difference with:
out.gif[0] GIF 1024x1024 1024x1024+0+0 8-bit sRGB 256c 16.7865MiB 0.010u 0:00.010 out.gif[1] GIF 516x516 1024x1024+252+257 8-bit sRGB 256c 16.7865MiB 0.010u 0:00.010 out.gif[2] GIF 515x520 1024x1024+248+257 8-bit sRGB 256c 16.7865MiB 0.010u 0:00.010 

The output GIFs have about the same size and look visually identical.

Elapsed (wall clock) time (h:mm:ss or m:ss): 0:56.16 Maximum resident set size (kbytes): 2676856 
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.41 Maximum resident set size (kbytes): 97172 
  • ImageMagick used 2.6Gb of RAM and took about 1 minute
  • ffmpeg used 100Mb of RAM and took 4 seconds

Test hardware: Lenovo ThinkPad P51 laptop, Intel Core i7-7820HQ, 32GB(16+16) DDR4 2400MHz SODIMM, 512GB SSD PCIe TLC OPAL2.

Источник

Конвертация изображений в любые форматы в Linux

В Linux имеется пакет ImageMagick, который поддерживает сотни форматов изображений и может конвертировать картинку любого формата в любой другой.

С конвертированием изображений (JPG и других форматов) отлично справляется утилиты convert и magick из пакета ImageMagick.

Подробности по установке ImageMagick, в том числе какие зависимости необходимо установить для поддержки максимального количества форматов, смотрите в статье: Руководство по ImageMagick: установка, использование и решение проблем

Полный список поддерживаемых форматов вы можете просмотреть командой

Также в конце статьи приведена таблица с полным перечнем поддерживаемых форматов файлов и ихкратким описанием.

Как конвертировать картинки в командной строке Linux

Чтобы конвертировать одно изображение в любой другой выполните команду вида:

magick КАРТИНКА РЕЗУЛЬТАТ

Примечание: если вы получили сообщение об ошибке, что команда magick не найдена, то вместо неё используйте команду convert. Объяснение будет дано ниже.

Программа автоматически определит исходный формат изображения.

Что касается формата выходного файла, то он определяется по указанному в предыдущей команде расширению.

magick КАРТИНКА.jpg РЕЗУЛЬТАТ.png

Следующая команда конвертирует файл image.png в формат JPG и сохранит новую картинку в файл image.jpg:

Вы также можете конвертировать динамические изображения (например, GIF файлы) в видео ролики (форматы avi, 3gp, webm, wmv, flv, mkv, mpg, webm, m2v, m4v, mov, mp4, mpeg и другие).

Также вы можете конвертировать видео форматы avi, 3gp, webm, wmv, flv, mkv, mpg, webm, m2v, m4v, mov, mp4, mpeg и другие в файлы GIF.

Как сжать изображение при конвертировании

О том, как одновременно конвертировать и уменьшить размер изображения смотрите в статье: Уменьшение размера фотографий. Массовое изменение размера фотографий в командной строке

Конвертация картинок во все форматы онлайн

Если вы не хотите устанавливать пакет ImageMagick или являетесь пользователем Windows, то вы можете воспользоваться онлайн конвертацией изображений в любые форматы. Это бесплатный онлайн сервис, вам достаточно указать картинку для конвертации и выбрать желаемый формат нового файла.

Источник

protrolium / terminal-gif.md

hypervoid force sizing + optimization:
convert -resize '1920x350!' -delay 5 -loop 0 *.png hv.gif
convert -fuzz 3% -resize '1920x350!' -delay 5 -loop 0 -coalesce -layers OptimizeTransparency *.png an.gif

this test yielded impressive reduction:
convert -filter Triangle -define filter:support=2 -thumbnail 1920 -delay 5 -loop 0 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB *.png output.gif

another version with less color information
convert -filter Triangle -define filter:support=2 -thumbnail 1920 -delay 5 -loop 0 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB -colors 32 -ordered-dither o8x8,8,8,8,4 +map *.png output.gif

convert GIF into movie by extracting frames and recompiling

convert -coalesce some.gif some%05d.png
extract gif frames

ffmpeg -i some%05d.png some.mov
converting image sequence in QuickTime 7 worked more effectively than the above command

rm some*.png
clear extracted frames

convert -coalesce animation.gif target.png

If you want the crop rectangle to start at top corner X: 50 Y: 100 and the crop rectangle to be of size W: 640 H:480, then use the command:
$ mogrify -crop 640x480+50+100 foo.png

To write the cropped image to a new file:
$ convert foo.png -crop 640x480+50+100 out.png

batch conversion:
for i in *.png; do convert "$i" -crop 1920x248+0+400 "$-cropped.png"; done

Источник

Convert every file from JPEG to GIF in terminal

This code to easy change write access to every text file in the folder. Now I was going to try to convert every jpg(even JPG) to gif in the same way but not sure if that is so easy. When I try with the convert command tools it wants to have an inputfilename and output filename but I do not think find give that so maybe find is not the right Tools to use?

Note that your example makes the *.txt files world-writable with that mode 666 . That is almost never a good idea.

Note that GIF supports upto 256 colours from a 24-bit palette. JPG supports 24-bit colours. You are likely to introduce dithering artefacts doing this

Well that is true that is not good idea to make every textfile 666 but when I did use this code I did have to do that to make some script work. Some file is GIF as default and some was JPG, that I have done now is just use at it is.

3 Answers 3

Find can be used for this, but I find it easier to use the shell instead. If your files are all in the same directory (no subdirectories) you can just do:

for f in /path/to/dir/*jpg /path/to/dir/*JPG; do convert "$f" "$.gif" done 

The $ syntax will remove the shortest match for the glob something from the end of the variable $var . For example:

$ var="foo.bar.baz" $ echo "$var : $" foo.bar.baz : foo.bar 

So here, it is removing the final extension from the filename. Therefore, "$.gif" is the original file name but with .gif instead of .jpg or .JPG .

If you do need to recurse into subdirectories, you can use bash's globstar option (from man bash ):

globstar If set, the pattern ** used in a pathname expansion con‐ text will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match. 

You can enable it with shopt -s globstar :

shopt -s globstar for f in /path/to/dir/**/*jpg /path/to/dir/**/*JPG; do convert "$f" "$.gif" done 

Источник

Читайте также:  Установка wifite2 kali linux
Оцените статью
Adblock
detector