R,ImageMagick:如何在动画的每个循环后添加延迟

时间:2018-11-27 22:12:34

标签: r imagemagick

我使用以下代码从一系列.png图像中创建了.gif动画:

gif <- function(name, imgDir, format, fps, delete) {


  require(magick)
  require(gtools)

  imgs <- mixedsort(list.files(path = imgDir, pattern = paste("*.", format, sep = "")))
  image <- image_read(paste(imgDir, "/", imgs, sep = ""))
  animation <- image_animate(image, fps = fps)
  image_write(animation, paste(name, ".gif", sep = ""))

  if (delete) unlink(paste(imgDir, "/*", sep = ""))


}



gif("animation", "tmp", "png", 10, TRUE)

动画.gif不断重复。我想在每个循环后添加x秒的延迟。是否有image_animate()的参数或用于此目的的参数?

1 个答案:

答案 0 :(得分:0)

使用 .gif 中单个帧的索引来构造一个带有“暂停”的新 .g​​if。您可以通过重复同一帧来创建暂停效果。使用 rep() 将“暂停”帧复制 N 次以控制暂停的长度。

从你的例子来看,如果你想停留在 gif 的最后一帧,你会想要这样的:

gif <- function(name, imgDir, format, fps, delete) {
  require(magick)
  require(gtools)
  imgs <- mixedsort(list.files(path = imgDir, pattern = paste("*.", format, sep = "")))
  image <- image_read(paste(imgDir, "/", imgs, sep = ""))
  animation <- image_animate(image, fps = fps)
  #Pause on the last frame for 1 second
  #Use c() to combine image frames from one or more magick gif objects  
  gif_with_pause<-c(animation, rep(animation[length(animation)],10))
  image_write(gif_with_pause, paste(name, ".gif", sep = ""))
}
gif("animation_with_pause", "tmp", "png", 10, TRUE)

对于有兴趣将 .gif 制作为图库的任何其他人,您可能需要查看 magick::image_morph(),它可以在图像之间添加漂亮的过渡。也可以延长单个帧出现的时间。您还可以通过将您的 gif 与第二个 gif(显示最后一帧平滑过渡到第一帧)相结合,使 GIF 平滑循环。让我提供一个两幅图像 gif 幻灯片的工作示例,该幻灯片在每个图像上平滑循环并暂停:

library(magick)
library(dplyr)
#read in some images
i1<-image_read("https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Ghostscript_Tiger.svg/512px-Ghostscript_Tiger.svg.png")                                                     
i2<-image_read("https://jeroen.github.io/images/frink.png")

#make a gif image
initial_gif<-image_resize(c(i1, i2), '200x200!') %>%
  image_background('white') %>%
  image_morph( frames = 10) %>%
  image_animate(optimize = TRUE, fps = 10)

#make another gif with the last image moving to the first image
last_img_to_1st_gif<-image_resize(c(i2,i1), '200x200!') %>%
  image_background('white') %>%
  image_morph( frames = 10) %>%
  image_animate(optimize = TRUE, fps = 10)

#use rep() to linger on the first image, cycle the gif, linger on the second image, 
#then show a transition back to the first image.
new_gif<-c(rep(initial_gif[1],10),
             initial_gif,
             rep(initial_gif[length(initial_gif)],10),
             last_img_to_1st_gif)

结果如下: example of gif as image gallery