设置帧延迟后保存动画 GIF 图像

时间:2021-06-06 12:31:22

标签: c# image

我想使用 System.Drawing.Image 中的 PropertyItems 修改动画 GIF 文件中的帧延迟。这很有效,但我无法将更改保存到文件中。

提前谢谢彼得

Win10 x64; .NET 框架 4.6.2

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Linq;

/// <summary>
/// Change delay and save to file.
/// </summary>
/// <param name="gifImage">the input-gif-image</param>
/// <param name="newDelay">new delay in 1/100 sec.</param>
/// <param name="fileToSave">full path to save the changed image</param>
private static void ChangeGifFrameDelayAndSave(Image gifImage, int newDelay, string fileToSave)
{
    // convert newDelay to raw bytes
    byte[] frameDelayBytes = BitConverter.GetBytes(newDelay);   //4 Bytes

    var frameDimension = new System.Drawing.Imaging.FrameDimension(gifImage.FrameDimensionsList[0]);
    int frameCount = gifImage.GetFrameCount(frameDimension);
    var framePropItem = gifImage.GetPropertyItem(0x5100);       //get propItem with frame-delays
    byte[] delayRawData = framePropItem.Value;

    // change delays in each frame
    for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
    {
        delayRawData[frameIndex * 4 + 0] = frameDelayBytes[0];
        delayRawData[frameIndex * 4 + 1] = frameDelayBytes[1];
        delayRawData[frameIndex * 4 + 2] = frameDelayBytes[2];
        delayRawData[frameIndex * 4 + 3] = frameDelayBytes[3];
    }

    // set propItem back to the image
    framePropItem.Value = delayRawData;
    gifImage.SetPropertyItem(framePropItem);

    // test only:
    {
        PictureBox1.Image = gifImage;  // THIS WORKS WELL: newDelay is applied to the image and I can see the change
    }

    // now save the Gif to file...
    gifImage.Save(fileToSave, System.Drawing.Imaging.ImageFormat.Gif);

    // unfortunately newDelay is NOT APPLIED to the file!
    // what I'm doing wrong :-(
}

1 个答案:

答案 0 :(得分:0)

在 Microsoft 显然没有发现有必要以可展示的方式实现 GDI+ 组件之后,我现在以完全不同的方式和低级别解决了这个问题。

感谢 Bjørn 提供的这个出色的解决方案(它是一个完整的具有 UI 的低级 Gif 编辑器):https://www.codeproject.com/Articles/1042433/Manipulating-GIF-Color-Tables?msg=5810217#xx5810217xx