Take Snapshots PART II – Save as animated GIF

I was asked, if it would be possible to save the snapshots created in my last post as an animated gif. With a DispatcherTimer and the GifBitmapEncoder-class you’re not far away from it. Just create a MediaElement in your Window:

<MediaElement Source="thomasOnBoard.wmv" 
  x:Name="media" MediaOpened="media_MediaOpened"
  MediaEnded="media_MediaEnded" Width="300"
  Height="200" Stretch="Fill"/>

In the Codebehind-File, implement Eventhandlers for MediaOpened and MediaEnded-Events. In MediaOpened you start the DispatcherTimer. I’ve just used an interval of 100 milliseconds. In the Tick-Eventhandler, which is called each 100 milliseconds, a BitmapFrame is added to the GifBitmapEncoders Frames-Property. When the video ends, the MediaEnded-Eventhandler writes the GIF to your disk and opens the file. That’s it. :-)

public partial class Window1 : Window
{
  ...
  GifBitmapEncoder _encoder;
  DispatcherTimer _timer;
  private void media_MediaOpened(object sender, ...)
  {
    _timer = new DispatcherTimer();
    _timer.Interval = TimeSpan.FromMilliseconds(100);
    _timer.Tick += OnTick;
    _timer.Start();
  }
  void OnTick(object sender, EventArgs e)
  {
    Size dpi = new Size(96, 96);
    RenderTargetBitmap bmp =
      new RenderTargetBitmap(300, 200,
        dpi.Width, dpi.Height, PixelFormats.Pbgra32);
    bmp.Render(media);

    if (_encoder == null)
      _encoder = new GifBitmapEncoder();
    
    _encoder.Frames.Add(BitmapFrame.Create(bmp));
  }

  private void media_MediaEnded(object sender, ...)
  {
    _timer.Tick -= OnTick;
    _timer = null;

    string filename = Guid.NewGuid().ToString() + ".gif";
  FileStream fs = new FileStream(filename, FileMode.Create);
    _encoder.Save(fs);
    fs.Close();
    _encoder = null;

    Process.Start(filename);
  }
}

Here’s the gif saved from my video. Just click on it to see it animated:

withWPFCreated

Share this post

Comment (1)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.