Dynamically creating thumbnails with WriteableBitmap and DispatcherTimer in Silverlight 3

Sat, Nov 7, 2009

Silverlight, Tutorials

In the previous example “Creating thumbnails of video frames with WriteableBitmap in Microsoft Expression Blend 3″ the user was able to create thumbnails by clicking on the video display.

The following example shows how thumbnails could be dynamically created by using DispatcherTimer thereby eliminating the need to click.

To stop the timer from firing, I simply hooked into the MediaElement mediaEnded event.

XAML code


<UserControl
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	x:Class="ImageSnapshot.MainPage"
	Width="605" Height="610" mc:Ignorable="d" Background="Black">

	<StackPanel  Orientation="Vertical" HorizontalAlignment="Stretch" Margin="10">
		<MediaElement x:Name="myMediaElement" Source="/Movie.wmv" Height="416" d:LayoutOverrides="HorizontalMargin" Cursor="Hand" MediaEnded="stopTimer"/>
		<ScrollViewer x:Name="scroller" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Hidden" Height="160" BorderBrush="{x:Null}" Margin="8,0">
			<StackPanel x:Name="thumbs" Orientation="Horizontal" Margin="0,5,0,10"  />
		</ScrollViewer>
	</StackPanel>
</UserControl>

C# code


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace ImageSnapshot
{
	public partial class MainPage : UserControl
	{
		System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();

		public MainPage()
		{
			InitializeComponent();

            myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
            myDispatcherTimer.Tick += new EventHandler(takeSnapShot);
            myDispatcherTimer.Start();
		}
		private void takeSnapShot(object o, EventArgs sender)
		{
			WriteableBitmap snapShot = new WriteableBitmap(myMediaElement, null);

			Image image = new Image();
			image.Height = 89;
			image.Margin = new Thickness(10);
			image.Source = snapShot;

			thumbs.Children.Add(image);
			scroller.UpdateLayout();
			double scrollPos = thumbs.ActualWidth;
			scroller.ScrollToHorizontalOffset(scrollPos);
		}

		private void stopTimer(object sender, System.Windows.RoutedEventArgs e)
		{
			myDispatcherTimer.Stop();
		}
	}
}

, , , , ,

Leave a Reply

You must be logged in to post a comment.