如何在 C# 中显示 GIF 图像的特定帧

本文关键字:图像 GIF 显示 | 更新日期: 2023-09-27 18:36:57

我想显示一个gif图像的框架。我搜索并发现以下代码应该有效,但它不起作用。它正确检测帧数,但它显示 GIF 的整个帧而不是指定的帧。谢谢大家。

Image[] frames = new Image[36];
Image GG = Image.FromFile(@"C:'Users'Administrator'TEST C#'TEST2frame2'chef.gif");
FrameDimension dimension = new FrameDimension(GG.FrameDimensionsList[0]);
            // Number of frames
int frameCount = GG.GetFrameCount(dimension);
label1.Text = frameCount.ToString();
            // Return an Image at a certain index
GG.SelectActiveFrame(dimension, 1);
frames[1] = ((Image)GG.Clone());
pictureBox1.Image = frames[1];

如何在 C# 中显示 GIF 图像的特定帧

使用您自己的代码,直到调用 SelectActiveFrame() 并在调用后更改为以下行:

frames[0] = new Bitmap(GG);
pictureBox1.Image = frame[0];

这应该可以解决问题。请不要忘记处理创建的图像。

哦,它有效,但不是你期望的那样。

当您设置 gif 图像的活动帧时,它实际上会从该帧重新启动其动画。例如,当您更改帧时,您必须通过将pictureBox.IsEnabled设置为 false 来停止它。尝试以下代码

private Image img;
public Form1()
{
    InitializeComponent();
    img = Image.FromFile(@"C:'Users'Administrator'TEST C#'TEST2frame2'chef.gif");
    pictureBox1.Image = img;
}
private void button1_Click(object sender, EventArgs e)
{
    var dim = new FrameDimension(img.FrameDimensionsList[0]);
    img.SelectActiveFrame(dim, 1);
    pictureBox1.Enabled = false;
}

尝试在不同的时刻按下按钮,您将看到活动图像帧将发生变化。