如何在.NET中分割动画GIF?

5

如何在 .net 中将动态gif图拆分成其组成部分?

具体而言,我想将它们加载到内存中的 Image(s) (System.Drawing.Image)。

======================

根据 SLaks 的答案,我现在有了以下代码:

public static IEnumerable<Bitmap> GetImages(Stream stream)
{
    using (var gifImage = Image.FromStream(stream))
    {
        //gets the GUID
        var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
        //total frames in the animation
        var frameCount = gifImage.GetFrameCount(dimension); 
        for (var index = 0; index < frameCount; index++)
        {
            //find the frame
            gifImage.SelectActiveFrame(dimension, index);
            //return a copy of it
            yield return (Bitmap) gifImage.Clone();
        }
    }
}
4个回答

5
使用SelectActiveFrame 方法选择包含动画 GIF 的Image实例的活动帧。例如:
image.SelectActiveFrame(FrameDimension.Time, frameIndex);

要获取帧数,请调用GetFrameCount(FrameDimension.Time)
如果您只想播放动画,您可以将其放入PictureBox中或使用ImageAnimator类。

2
// Parses individual Bitmap frames from a multi-frame Bitmap into an array of Bitmaps

private Bitmap[] ParseFrames(Bitmap Animation)
{
    // Get the number of animation frames to copy into a Bitmap array

    int Length = Animation.GetFrameCount(FrameDimension.Time);

    // Allocate a Bitmap array to hold individual frames from the animation

    Bitmap[] Frames = new Bitmap[Length];

    // Copy the animation Bitmap frames into the Bitmap array

    for (int Index = 0; Index < Length; Index++)
    {
        // Set the current frame within the animation to be copied into the Bitmap array element

        Animation.SelectActiveFrame(FrameDimension.Time, Index);

        // Create a new Bitmap element within the Bitmap array in which to copy the next frame

        Frames[Index] = new Bitmap(Animation.Size.Width, Animation.Size.Height);

        // Copy the current animation frame into the new Bitmap array element

        Graphics.FromImage(Frames[Index]).DrawImage(Animation, new Point(0, 0));
    }

    // Return the array of Bitmap frames

    return Frames;
}

这种技术(用 C## 编写)比 Clone() 方法更具优势,因为 Clone() 方法会为每一帧复制整个动画,从而使存储所有帧所需的内存量增加了平方倍数(例如,Clone() 方法产生一个动画数组,其中每个副本都有不同的当前帧)。为了真正分解动画帧,每个帧都需要在数组中绘制成自己的 Bitmap。根据需要,一旦将动画解析为帧数组,就可以将其处理掉以进行垃圾回收... - Neoheurist

0
Image img = Image.FromFile(@"D:\images\zebra.gif");
//retrieving 1st frame
 img.SelectActiveFrame(new FrameDimension(img.FrameDimensionsList[0]), 1);
 pictureBox1.Image = new Bitmap(img);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接