【matlab】生成 GIF 的函数(已封装可直接调用)


文章目录


前言

生成 gif 图片时遇到的问题,为了后续调用方便,封装为函数


一、函数输入与输出

  • 输入:
    • cell_figure: cell 数组,数组元素是活动窗口的结构体
      • 由 drawnow; F=getframe(gcf) 得到
    • name: string, 图片的名称
  • 输出
    • 无输出,生成一张名为 name 的 GIF 图像

二、函数代码

matlab 复制代码
%% write_gif() function,可以生成 GIF 的函数
%
% 输入参数:
%   input1: cell(struct), stru. describe the graph frame
%   input2: string, name of file
%
% 输出参数:
%   无输出,生成一个 GIF 图片


function write_gif(cell_figure, name)
    % init
    pic_num = 1;
    name = string(name); % be str

    for i = 1: length(cell_figure)
        graph_struct_i = cell_figure{i};
        
        % frame 2 image
        I=frame2im(graph_struct_i);
        [I,map]=rgb2ind(I,256);
    
        % 写入 gif 文件
        if pic_num == 1
            imwrite(I, map, name + '.gif', 'gif', 'Loopcount', inf, 'DelayTime', 0.2);
        else
            imwrite(I, map, name + '.gif', 'gif', 'WriteMode', 'append', 'DelayTime', 0.2);
        end
    
        % pic_num add
        pic_num = pic_num + 1;
    end
end

三、例程(可直接运行)

matlab 复制代码
clear; clc; close all;

%% create line

% init
cell_figure = {};

for i = 1:5
    
    % create fig
    fig = plot([i, 2 + i*2, -3 + i*3, 7 - i*4]);
    ylim([-20, 20])

    % draw & write cell
    drawnow;
    F=getframe(gcf);
    cell_figure{end+1} = F;

end

% invoke
write_gif(cell_figure, 'test_1')


%% write_gif() function,可以生成 GIF 的函数
%
% 输入参数:
%   input1: cell(struct), stru. describe the graph frame
%   input2: string, name of file
%
% 输出参数:
%   无输出,生成一个 GIF 图片


function write_gif(cell_figure, name)
    % init
    pic_num = 1;
    name = string(name); % be str

    for i = 1: length(cell_figure)
        graph_struct_i = cell_figure{i};
        
        % frame 2 image
        I=frame2im(graph_struct_i);
        [I,map]=rgb2ind(I,256);
    
        % 写入 gif 文件
        if pic_num == 1
            imwrite(I, map, name + '.gif', 'gif', 'Loopcount', inf, 'DelayTime', 0.2);
        else
            imwrite(I, map, name + '.gif', 'gif', 'WriteMode', 'append', 'DelayTime', 0.2);
        end
    
        % pic_num add
        pic_num = pic_num + 1;
    end
end
  • 输出结果

参考文献

1\] https://blog.csdn.net/lusongno1/article/details/78632457


相关推荐
阿蓝灬19 分钟前
React中的stopPropagation和preventDefault
前端·javascript·react.js
天天向上102422 分钟前
vue3 抽取el-dialog子组件
前端·javascript·vue.js
lecepin27 分钟前
AI Coding 资讯 2025-11-05
前端·javascript
excel30 分钟前
Vue 模板解析器 parserOptions 深度解析
前端
前端小咸鱼一条34 分钟前
17.React获取DOM的方式
前端·javascript·react.js
excel36 分钟前
Vue 编译核心中的运行时辅助函数注册机制详解
前端
excel37 分钟前
🌿 深度解析 Vue DOM 编译器模块源码:compile 与 parse 的构建逻辑
前端
excel38 分钟前
深度解析 Vue 编译器中的 transformShow:v-show 指令的编译原理
前端
excel39 分钟前
深度解析:decodeHtmlBrowser —— 浏览器端 HTML 解码函数设计
前端
excel39 分钟前
深度解析:Vue 模板编译器中的 transformVText 实现原理
前端