saveGIF() returns 空 GIF

saveGIF() returns empty GIF

在 R 中,我试图获得基于多张图像的动画 GIF。我写了一个返回图像的函数,并使用动画包的 saveGIF() 函数来创建 GIF。返回图像的函数有效(我看到图像在查看器中弹出)。使用 saveGIF 创建 GIF 时,没有错误消息,但 GIF 为空。

 library(leaflet)
 library(mapview)
 library(animation)

  latitude = c(seq(48.13608, 52.48608, 0.00145))
  longitude = c(seq(11.57278, 13.40278, 0.00061))

  sampledf <- as.data.frame(cbind(longitude, latitude))


  plot.1 <- function(df)
  {
  for (i in seq(1,nrow(df),300)){
  m<- leaflet() %>%
  addTiles() %>%
  setView( lng = 12.48778
           , lat = 50.31108
           , zoom = 4 )    %>%

  addPolylines(data = df[1:i,],
               lng = ~longitude,
               lat = ~latitude,
               color = ~"red")

  print(m)
 }
 }

  saveGIF(plot.1(sampledf),movie.name="test.gif", interval=0.5, ani.width=1980/2, ani.height=1080/2)

这可能是一种复杂的方法,但我可以通过首先为 sampledf 数据创建 png 文件然后使用 magick 库来生成 gif 来实现。

library(leaflet)
library(mapview)
library(magick)

counter <- 1 
for (i in seq(1,nrow(sampledf),300)){

    m <- leaflet() %>%
          addTiles() %>%
          setView( lng = 12.48778
                 , lat = 50.31108
                 , zoom = 4 )    %>%
           addPolylines(data = sampledf[1:i,],
                        lng = ~longitude,
                        lat = ~latitude,
                        color = ~"red")

     mapshot(m, file = paste0("plot_", counter, ".png"))
     counter = counter + 1
}
file_names <- list.files(pattern = "plot_\d+.png$", full.names = TRUE)

image_read(file_names) %>%
   image_animate(fps = 1) %>%
   image_write("output.gif")