7

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?

Soheil
  • 193
  • 4
  • 10

2 Answers2

12

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
JMilner
  • 491
  • 4
  • 12
7

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.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225