Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multiple png to gif as an animation in R

I have a bunch of png files in a directory and I want to convert them into a gif (animated) file via R. Can you please advise how to do that?

like image 621
Soheil Avatar asked May 31 '19 06:05

Soheil


People also ask

How do you make an animated gif from multiple pictures?

If you use Google Photos on Android (or iOS), you can make an animated GIF from a selection of your pictures. Just tap Library, then Utilities and Create New. Choose Animation, select the photos and tap Create.


2 Answers

Here is some dummy code you can use:

First use the magick package for the GIF Use the magrittr package or the dplyr package for the %>%

library(magick)
library(magrittr)

Then list files in the directory, and combine into gif fps is frames per second

list.files(path='/$PATH/', pattern = '*.png', full.names = TRUE) %>% 
        image_read() %>% # reads each path file
        image_join() %>% # joins image
        image_animate(fps=4) %>% # animates, can opt for number of loops
        image_write("FileName.gif") # write to current dir
like image 94
JMilner Avatar answered Sep 20 '22 14:09

JMilner


A solution with the gifski package:

library(gifski)
png_files <- list.files("path/to/your/pngs/", pattern = ".*png$", full.names = TRUE)
gifski(png_files, gif_file = "animation.gif", width = 800, height = 600, delay = 1)

The advantage of gifski is that the number of colors in the GIF is not limited to 256.

like image 40
Stéphane Laurent Avatar answered Sep 20 '22 14:09

Stéphane Laurent