ほんじゃらねっと

ダイエット中プログラマのブログ

SilverlightでWebカメラの映像を表示する

こちらを参考に作成した。
http://msdn.microsoft.com/ja-jp/library/ff602282(v=vs.95).aspx


Webカメラに接続して映像を画面上に表示できるだけのサンプル。
BrushとしてRectangleのFillに設定してるので、Brushが設定できるところなら
どこでも映像を表示できるっぽい。
画像を切り出して保存もできるらしいので、色々面白いことできそうだなぁ。思いつかないけど。


MainPage.xaml

<UserControl x:Class="CameraTest.MainPage"
    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"
    mc:Ignorable="d"
    d:DesignHeight="500" d:DesignWidth="600">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox x:Name="Devices" Grid.Column="0">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FriendlyName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="Start" x:Name="StartButton" Click="StartButton_Click" />
<Button Grid.Column="2" Content="Stop" x:Name="StopButton" Click="StopButton_Click" />
</Grid>
<Rectangle Grid.Row="1" x:Name="webcamDisplay" Width="150" Height="100" Stroke="Black" />
</Grid>
</UserControl>


MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace CameraTest
{
public partial class MainPage : UserControl
{
CaptureSource captureSource = new CaptureSource();
public MainPage()
{
InitializeComponent();
Devices.ItemsSource = CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();
VideoBrush webcamBrush = new VideoBrush();
webcamBrush.SetSource(captureSource);
webcamDisplay.Fill = webcamBrush;
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
captureSource.VideoCaptureDevice = (VideoCaptureDevice)Devices.SelectedItem;
if (CaptureDeviceConfiguration.RequestDeviceAccess() && captureSource.VideoCaptureDevice != null)
{
try
{
captureSource.Start();
}
catch (InvalidOperationException ex)
{
MessageBox.Show("カメラの起動に失敗しました");
}
}
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
if (captureSource.VideoCaptureDevice != null)
{
captureSource.Stop();
}
}
}
}