简体   繁体   English

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

[英]Save animated GIF image after set frame-delay

I want to modify the frame-delay in animated GIF files using the PropertyItems in System.Drawing.Image.我想使用 System.Drawing.Image 中的 PropertyItems 修改动画 GIF 文件中的帧延迟。 This works well, but I'm not able to save the changes to file.这很好用,但我无法将更改保存到文件中。

Thx in advance, Peter提前谢谢,彼得

Win10 x64; Win10 x64; .NET Framework 4.6.2 .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 :-(
}

After Microsoft apparently didn't find it necessary to implement the GDI+ components in a presentable way, I have solved the problem now completely differently and low-level.在微软显然没有发现有必要以一种像样的方式实现 GDI+ 组件之后,我现在已经完全不同地和低级地解决了这个问题。

Thanks to Bjørn for this excellent solution (it's a complete low-level Gif-Editor with UI): https://www.codeproject.com/Articles/1042433/Manipulating-GIF-Color-Tables?msg=5810217#xx5810217xx感谢 Bjørn 的出色解决方案(它是一个完整的低级 Gif 编辑器,带有 UI): https://www.codeproject.com/Articles/1042433/Manipulating-GIF-Color-Tables?msg=5810217#xx5810217xx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM