Soheil
Soheil

Reputation: 333

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?

Upvotes: 9

Views: 7201

Answers (2)

Stéphane Laurent
Stéphane Laurent

Reputation: 84699

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.

Upvotes: 8

JMilner
JMilner

Reputation: 531

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

Upvotes: 16

Related Questions