2009-11-11 3 views
4

Как вы разбиваете анимированный gif на свои составные части в .net?Как разбить анимированный gif на .net?

В частности, я хочу загрузить их в изображение (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

+0

спасибо слайсам. Обновлено :) – Simon

ответ

3

Используйте метод SelectActiveFrame для выбора активного кадра экземпляра Image с анимированным GIF. Например:

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; 
} 
+0

Этот метод (написанный на 'C##') имеет преимущество перед подходом 'Clone()', потому что подход 'Clone()' копирует всю анимацию для каждого кадра, по существу, возлагая квадрат на объем памяти, необходимый для хранения всех (например, подход 'Clone()' дает массив анимаций, где каждая копия имеет другой текущий кадр). Для того, чтобы по-настоящему разобрать отдельные кадры анимации, каждый из них должен быть втянут в собственный битмап в массиве. При необходимости, после того, как анимация проанализирована в массив кадров, она может быть утилизирована для сбора мусора ... – 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); 
Смежные вопросы