You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Dart image包生成GIF,是否支持自定义帧率?

问题

我通过image包从临时目录的图片集生成了动画GIF,但不确定能不能自定义生成GIF的帧率。当前生成代码如下:

void _mergeScreenshotsIntoGif({
    required int gameStepsCount,
    required String tempStorageDirPath,
    required String baseFilename,
  }) async {
    final animation = image.Animation();
    final imageDecoder = image.PngDecoder();
    for (var stepIndex = 1; stepIndex <= gameStepsCount; stepIndex++) {
      final currentFile = File(
          '$tempStorageDirPath${Platform.pathSeparator}${baseFilename}_$stepIndex.png');
      final currentImageBytes = await currentFile.readAsBytes();
      final currentImage = imageDecoder.decodeImage(currentImageBytes)!;
      animation.addFrame(currentImage);
    }
    final gifData = image.encodeGifAnimation(animation);
    if (gifData == null) {
      //TODO handle gif generation error
      return;
    }
    final destinationFile =
        File('$tempStorageDirPath${Platform.pathSeparator}$baseFilename.gif');
    await destinationFile.writeAsBytes(gifData);
  }

我查看了该包的文档,但没找到相关解决方案,请问这是否可行?

解答

当然可以自定义帧率,有两种简单的实现方式:

  • 给单帧设置延迟时间
    每个添加到Animation的帧都能单独设置延迟(单位为1/100秒)。比如要实现10帧每秒(FPS),每帧的延迟就是10(计算逻辑:100/10=10),修改addFrame调用即可:
// 设置单帧延迟为10(对应10 FPS)
animation.addFrame(currentImage, duration: 10);
  • 全局统一设置帧延迟
    如果所有帧的帧率一致,也可以在调用encodeGifAnimation时传入frameDuration参数,一次性给所有帧设置相同延迟:
// 全局设置每帧延迟10(对应10 FPS)
final gifData = image.encodeGifAnimation(animation, frameDuration: 10);

换算逻辑参考:延迟时间(1/100秒)= 100 / 目标FPS。比如20 FPS对应延迟5,5 FPS对应延迟20。

内容的提问来源于stack exchange,提问作者loloof64

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:30:52