r - 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()
用于目的的参数或其他东西?
解决方案
使用 .gif 中各个帧的索引来构造一个带有“暂停”的新 .gif。您可以通过重复同一帧来创建暂停效果。用于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)
推荐阅读
- c# - 使用 Dropbox .NET SDK 上传文件未完成
- jquery - 使用 JSON 数组和对象
- javascript - React Native 的功能不会更新状态/不会改变 UI
- html - 如何将文本放置在与图像相同的高度
- python-3.x - 是否可以(永久)更改 matplotlib 图的默认样式和大小(在 Jupyer 笔记本中内联绘制)?
- c++ - 浮点数是否以 0.5 结尾。C++
- java - 在 Web 控制台以外的地方访问 H2 嵌入式数据库?
- scala - Spark - 给定单词后出现频率最高的单词
- python - 如何在 Python 中使用 Kerberos 库?
- ruby-on-rails - Ruby on Rails:使用 ransack 在日期范围之间进行查询