2009-11-11 59 views
4

如何在.net中將動畫gif分割爲其組成部分?如何在.net中分割動畫gif?

具體而言,我想將它們加載到內存中的圖像(S)(System.Drawing.Image)。

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

基於SLaks的回答,我現在這個

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

當你通過在'using'塊包裝的代碼之後,你應該處理的圖像。 – SLaks 2009-11-11 03:20:41

+0

謝謝slaks。更新:) – Simon 2009-11-11 03:57:48

回答

3

使用SelectActiveFrame方法選擇一個擁有動畫GIF的Image實例的活動幀。例如:

image.SelectActiveFrame(FrameDimension.Time, frameIndex); 

要得到的幀數,撥打GetFrameCount(FrameDimension.Time)

如果你只是想播放動畫,你可以把它變成一個圖片或使用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; 
} 
+0

這種技術(用'C##'編寫)比'Clone()'方法具有優勢,因爲'Clone()'方法複製每個幀的整個動畫,基本上減少了存儲所有內存所需的內存量(例如'Clone()'方法產生一個動畫陣列,其中每個副本具有不同的當前幀)。 爲了真正解析動畫幀,每個動畫幀都需要被繪製到它自己的陣列內的「位圖」中。 根據需要,一旦動畫被解析成幀數組,它可以被處置爲垃圾收集... – Neoheurist 2014-10-03 11:54:31

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);