How to display MJPEG camera stream in a basic example program using ASP.NET

This example demonstrates a simple method for how you can display MJPEG camera stream in a basic example program in C# [ASP.NET]. To implement this example, you must have Ozeki Camera SDK installed, and a reference to OzekiSDK.dll should be added to your Visual Studio project.
Please follow the steps of this video tutorial if you would like to know how to stream the image of the camera in C#.

How to display MJPEG camera stream via example program using C#?

To establish the connection properly between your application and an IP camera you should apply the same code snippet what you have used in the example (How to connect to an IP camera device using C#?). Important: you should study this article in order to find out how to setup your Windows Forms/WPF Application correctly.

Getting started

To get started it is recommended to Download and Install the latest version of Ozeki Camera SDK. After installation you can find the example code discussed in this page with full source code in the following location on your harddisk:

To compile this example you will need Microsoft Visual Studio installed on your computer.


Properties:

  • Clients : It is a list of the clients who connected to the stream.
  • IsRunning: It is a logical value which indicates whether the stream is started or not.
  • ListenAddress:It is the URL path of the stream.
  • ListenPort:It is the port number of the source.
  • VideoChannel:It is the video chanel of the stream.

Methods:

  • Start(): By calling the Start() method the video stream is starting.
  • Stop(): By calling the Start() method you can stop the video stream.

Events:

  • ClientConnected: This event run if a new client connect. You can decide what you want to do with this client. For example you can log this connection or you can block it based on IP address.
  • ClientDisconnected: This event run if a client disconnect. Similar the ClientConnected event you can decide what you do.

As we are writing our program, we will have to use different objects:

MJPEGStreamer: This object is used for video steaming to the example program.
In the following rows you subscribe to the MJPEGStream's 2 events. The first one is for sending the image to the connected client. The second one is for stopping the stream if the client disconnects. streamer.ClientConnected += streamer_ClientConnected;
streamer.ClientDisconnected += streamer_ClientDisconnected;


MediaConnector: With the help of this object, we can connect different VideoHandler objects.
In this example the connector.Connect(camera.VideoChannel, streamer.VideoChannel); line connects the VideoChannel which comes from the camera, with the MJPEGSteamer's VideoChannel. That means it will display the image of the camera in the basic program every time, when a client opens it.


camera = new WebCamera()
We must choose the camera which we want to use. In the example below, we will use the default camera connected to our PC.


_streamer = new MJPEGStreamer(ip.ToString(), 1234);
After it is done, when you are creating the MJPEGStreamer object, you have to give the IP address and the port number of your computer, through which the web browser will retrieve the camera image.
You can ask your IP adress in the following row var IP = NetworkAddressHelper.GetLocalIP();

MJPEG camera stream viewer example program in C#

WPF  

BasicMJPEGViewer.cs


using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using Ozeki.Media;
using Ozeki.Camera;
using Ozeki.Network;

// 
// You have to add Ozeki Camera SDK reference. 
// You can download from here:  https://ozeki-sms-gateway.com/p_595-how-to-configure-the-firewall-for-smpp.html// 

namespace BasicMJPEGViewer
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        private DrawingImageProvider _provider;
        private IWebCamera _webCamera;
        private MediaConnector _connector;
        private MJPEGStreamer _streamer;
        private IVideoSender _videoSender;


        public MainWindow()
        {
            InitializeComponent();
            StartMJPEGStreamerButton.IsEnabled = false;
            OpenInBrowserButton.IsEnabled = false;
            StopMJPEGStreamerButton.IsEnabled = false;

            _connector = new MediaConnector();
            _provider = new DrawingImageProvider();

            VideoViewer.SetImageProvider(_provider);


            var ip = NetworkAddressHelper.GetLocalIP();
            _streamer = new MJPEGStreamer(ip.ToString(), 1234);
            SourceLabel.Content = "Source address: " + _streamer.ListenAddress;

            string fileContent = CreateHTMLPage(_streamer.ListenAddress);
            HtmlBox.Text = fileContent;
        }

        private void ConnectToCameraButton_Click(object sender, RoutedEventArgs e)
        {
            _webCamera = WebCameraFactory.GetDefaultDevice();

            if (_webCamera == null)
            {
                ConnectToCameraButton.IsEnabled = true;
                StartMJPEGStreamerButton.IsEnabled = false;
                MessageBox.Show("No camera detected.", "NOCAM");
            }
            else
            {
                ConnectToCameraButton.IsEnabled = false;
                StartMJPEGStreamerButton.IsEnabled = true;

                connector.Connect(_webCamera.VideoChannel, provider);
                videoSender = webCamera.VideoChannel;

                _webCamera.Start();
                VideoViewer.Start();
            }
        }

        private void StartMJPEGStreamerButton_Click(object sender, RoutedEventArgs e)
        {
            StartMJPEGStreamerButton.IsEnabled = false;
            OpenInBrowserButton.IsEnabled = true;
            StopMJPEGStreamerButton.IsEnabled = true;

            connector.Connect(_videoSender, streamer.VideoChannel);

            streamer.ClientConnected += streamer_ClientConnected;
            streamer.ClientDisconnected += streamer_ClientDisconnected;
            streamer.Started += streamer_Started;
            streamer.Stopped += streamer_Stopped;

            _streamer.Start();
        }

        private void _streamer_Started(object sender, System.EventArgs e)
        {
            StreamerStateLabel.Content = "State: Running";
        }

        private void _streamer_Stopped(object sender, System.EventArgs e)
        {
            StreamerStateLabel.Content = "State: Not running";
        }

        private void StopMJPEGStreamerButton_Click(object sender, RoutedEventArgs e)
        {
            StopMJPEGStreamerButton.IsEnabled = false;
            StartMJPEGStreamerButton.IsEnabled = true;
            OpenInBrowserButton.IsEnabled = false;

            _streamer.Stop();
            connector.Disconnect(_videoSender, streamer.VideoChannel);
        }

        private void OpenInBrowserButton_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("test.html");
        }

        private void _streamer_ClientConnected(object sender, VoIPEventArgs<IMJPEGStreamClient> e)
        {
            e.Item.StartStreaming();
        }

        private void _streamer_ClientDisconnected(object sender, VoIPEventArgs<IMJPEGStreamClient> e)
        {
            e.Item.StopStreaming();
        }

        private string CreateHTMLPage(string source)
        {
            StringBuilder sb = new StringBuilder();
            using (var fs = new FileStream("test.html", FileMode.Create))
            {
                using (var w = new StreamWriter(fs, Encoding.UTF8))
                {
                    sb.AppendLine("<html>");
                    sb.AppendLine("<head></head>");
                    sb.AppendLine("\t<body>");
                    sb.AppendLine("\t\t<img id='cameraImage' style='height: 100%;' src='" + source + "' alt='camera_image'/>");
                    sb.AppendLine("\t</body>");
                    sb.Append("</html>");

                    w.Write(sb.ToString());
                }
            }
            return sb.ToString();
        }
       
    }
}
		
Code 1 - MJPEG camera stream example program in C# [ASP.NET]


Basic Program

gui of an application for displaying mjpeg camera stream in c#
Figure 1 - The example program

After the successful implementation of the functions the application will work properly. Building and running will load in the image of the IP camera device connected to your PC into the example program.

Below you can find the code of the WebForm.aspx file of the previously presented application. With the help of this section your ASP.NET Application will be able to work properly.

WPF version


<Window
        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"
        xmlns:local="clr-namespace:BasicMJPEGViewer"
        xmlns:Media="clr-namespace:Ozeki.Media;assembly=OzekiSDK" x:Class="BasicMJPEGViewer.MainWindow"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        Title="MJPEGViewer Example" Height="448" Width="746"
        ResizeMode="NoResize"
    >
    
    <Grid<
        <GroupBox Header="Step 1 - Connect to USB camera" HorizontalAlignment="Left" VerticalAlignment="Top" Height="60" Width="200">
            <Grid>
                <Button x:Name="ConnectToCameraButton" Content="Connect" HorizontalAlignment="Center" VerticalAlignment="Top" Width="75" Margin="0,10,0,0" Click="ConnectToCameraButton_Click"/>
            </Grid>
        </GroupBox>
        <GroupBox Header="Step 2 - Start MJPEGStreamer" HorizontalAlignment="Left" VerticalAlignment="Top" Height="86" Width="200" Margin="0,65,0,0">
            <Grid>
                <Label x:Name="StreamerStateLabel" Content="State: Not running" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0>
                <Button x:Name="StartMJPEGStreamerButton" Content="Start" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="10,30,0,0" Click="StartMJPEGStreamerButton_Click"/>
                <Button x:Name="StopMJPEGStreamerButton" Content="Stop" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,30,10,0" Click="StopMJPEGStreamerButton_Click"/>
            </Grid>
        </GroupBox>
        <GroupBox Header="Step 3 - Open in default browser" HorizontalAlignment="Left" VerticalAlignment="Top" Height="60" Width="200" Margin="0,156,0,0>
            <Grid>
                <Button x:Name="OpenInBrowserButton" Content="Open" HorizontalAlignment="Center" VerticalAlignment="Top" Width="75" Margin="0,10,0,0" Click="OpenInBrowserButton_Click"/>
            </Grid>
        </GroupBox>
        
        <Media:VideoViewerWPF Name="VideoViewer" Background="Black" HorizontalAlignment="Center" VerticalAlignment="Top" Height="210" Width="280" Margin="175,10,0,0"/>
        
        <GroupBox Header="Example" HorizontalAlignment="Left" VerticalAlignment="Top" Height="190" Width="730" Margin="0,220,0,0">
            <Grid>
                <Label x:Name="SourceLabel" Content="Source address: " HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,5,0,0"/>
                <Label Content=".html file content:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,30,0,0"/>
                <TextBox x:Name="HtmlBox" IsReadOnly="True" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,55,0,0" Width="708" Height="103"/>
            </Grid>
        </GroupBox>

    </Grid>
</Window>

		
Code 2 - JPEG camera stream example program in C# [ASP.NET]

DISCLAIMER: Please note that the following features will only work if your IP camera supports the given function. You should check the user manual of your IP camera to make sure it supports the feature that you wish to implement in C#.

Related Pages

FAQ

Below you can find the answers for the most frequently asked questions related to this topic:

  1. How can I get the URL of the camera?

    You can get the URL from the producer of the camera. (In the 10th tutorial you can find information on how to create an own IP camera discoverer program.)

  2. I have not managed to build the solution. How to solve it?

    • Please set the Target framework property of the project to .NET 4.0.
    • You should add the System.Drawing.dll and the OzekiSDK.dll to the references of the solution.
    • Please import the missing classes.

More information