Skip to main content

Camera

Namespace: Wisej.Web.Ext.Camera

Assembly: Wisej.Web.Ext.Camera (4.1.0.0)

The Camera component makes it possible to take pictures with the device's camera and upload them to the server.

public class Camera : Control, IWisejHandler

The video stream starts automatically as soon as the control is rendered with Video set to true; there is no explicit Start method. Set Video to false (or dispose the control) to release the device.

The application must be served over HTTPS (or localhost), otherwise the browser will not grant access to the camera. When the user denies permission, the failure is reported through the Error event; no exception is thrown on the server.

Example:

This example adds a camera preview to a form and lets the user start and stop the stream.

using Wisej.Web;
using Wisej.Web.Ext.Camera;

public partial class Form1 : Form
{
private Camera camera;

public Form1()
{
InitializeComponent();

this.camera = new Camera
{
Dock = DockStyle.Fill,
Video = true, // starts the stream on render
Audio = false,
Mirror = true, // selfie-style preview
ObjectFit = ObjectFit.Cover,
FacingMode = Camera.VideoFacingMode.User, // Environment = rear camera
WidthCapture = 1280,
HeightCapture = 720
};

this.camera.Error += (s, e) =>
AlertBox.Show(e.Message, MessageBoxIcon.Error);

this.Controls.Add(this.camera);
}

// Turning the stream off releases the device and turns off the camera LED.
private void stopButton_Click(object sender, EventArgs e)
=> this.camera.Video = false;

private void startButton_Click(object sender, EventArgs e)
=> this.camera.Video = true;
}

// Picking a specific camera:
var devices = await this.camera.GetDevicesAsync(refresh: true);
this.camera.DeviceName = devices.FirstOrDefault(); // matches the browser's device label

Constructors​

Instance member Camera()​

Initializes a new instance of the Camera class.

Properties​

Instance member Audio​

Boolean: Gets or sets a value indicating whether audio recording is enabled. (Default: False)

Value: true if audio should be recorded; otherwise, false.

This property controls the audio capture capability of the camera extension. When set to true, audio will be recorded alongside the video stream.

Instance member BorderStyle​

BorderStyle: Gets or sets the border style of the control. (Default: Solid)

Value: A BorderStyle value that specifies the border style. The default value is None.

Instance member DeviceName​

String: Gets or sets the name of the video device to be used for capturing video input. (Default: "")

If the DeviceName is not specified or if it refers to an invalid device, the first available video device returned by the browser will be used by default.

Example:

string deviceName = camera.DeviceName;
AlertBox.Show($"Current device: {deviceName}");

Instance member FacingMode​

VideoFacingMode: Gets or sets the direction the camera producing the video track is facing.

Possible values are:

  • User — faces the user, e.g. the front camera on a smartphone.
  • Environment — faces away from the user, e.g. the rear camera.
  • Left — faces the user from their left.
  • Right — faces the user from their right. (Default: User)

Value: A VideoFacingMode value representing the camera's facing mode. The default is User.

This property is relevant only on devices with more than one camera, typically phones and tablets. On desktop browsers the constraint is generally ignored and the default device is used. Use DeviceName to select a specific camera instead.

For more information on camera facing modes, see facingMode.

Example:

Switching to the rear-facing camera:

this.camera.FacingMode = Camera.VideoFacingMode.Environment;

See also: DeviceName

Instance member HeightCapture​

Int32: Gets or sets the height of the video capture resolution in pixels. This property defines the vertical dimension of the video feed from the camera. (Default: True)

Value: An integer representing the height of the video capture resolution. The value must be a positive integer, typically in accordance with standard video resolutions.

Example:

int captureHeight = camera.HeightCapture;
camera.HeightCapture = 720; // Set height to 720 pixels

Instance member Mirror​

Boolean: Gets or sets a value indicating whether the media output should be mirrored. When set to true, the media will be displayed as a mirrored image, which is commonly used for cameras to provide a preview that reflects the way a user sees themselves. (Default: False)

Value: true if the media is to be mirrored; otherwise, false.

Example:

camera.Mirror = true; // Enable mirroring for the camera output

Instance member ObjectFit​

ObjectFit: Gets or sets the ObjectFit property that specifies how the content of a video should be resized to fit its container. (Default: True)

The ObjectFit property determines the method by which the video content is adjusted to match the dimensions of its container. Refer to the following link for more information on CSS object-fit values: css3_object-fit.

Example:

This example shows how to set the object fit for the camera:

camera.ObjectFit = ObjectFit.Cover;

Instance member Video​

Boolean: Gets or sets a value indicating whether video recording is enabled. (Default: True)

Value: true if video recording should be enabled; otherwise, false.

When set to true, the camera will record video. Ensure that the necessary permissions and resources are available for video recording to function properly.

Instance member VideoFilter​

String: Gets or sets the CSS filter to apply to the video stream, enhancing its appearance or applying visual effects. For more information on available filter options, refer to the filter. (Default: null)

Example:

///

// Full grayscale.
camera.VideoFilter = "grayscale(100%)";

Instance member WidthCapture​

Int32: Gets or sets the width of the video capture resolution, measured in pixels. This property determines the horizontal dimension of the captured video, allowing for adjustments to optimize video quality or performance based on the target display format. (Default: True)

Value: An integer representing the width of the video capture resolution in pixels. The default value is typically set by the camera configuration or underlying framework.

Example:

camera.WidthCapture = 1280; // Set the video capture width to 1280 pixels
int currentWidth = camera.WidthCapture; // Retrieve the current video capture width

Instance member Zoom​

Int32: Gets or sets the zoom level of the camera. The zoom value adjusts the camera's field of view, allowing you to zoom in or out on the scene captured by the camera. (Default: 1)

Value: An integer representing the zoom level. Positive values indicate zooming in, while negative values indicate zooming out. The range of acceptable values may vary depending on the specific camera implementation.

Please note that not all camera models support zoom functionality. Ensure that the camera in use has zoom capabilities before modifying this property.

Example:

camera.Zoom = 5; // Set zoom to a value for zooming in
camera.Zoom = -3; // Set zoom to a value for zooming out

Methods​

Instance member GetDevices(callback)​

Asynchronously retrieves the names of the available video devices and invokes the specified callback with the results.

ParameterTypeDescription
callbackAction<String[]>The callback method that will be invoked with an array of device names. This parameter must not be null.

Throws:

Example:

camera.GetDevices(deviceNames =>
{
foreach (var name in deviceNames)
{
Console.WriteLine(name);
}
});

Instance member GetDevices(refresh, callback)​

Retrieves the names of the video devices (cameras) available on the client.

ParameterTypeDescription
refreshBooleanA bool that indicates whether to re-read the list of devices from the browser. If true, the device list is enumerated again; otherwise the list cached on the client is used.
callbackAction<String[]>An Action delegate invoked with the array of device names once the client responds.

The names are the labels the browser reports for its video input devices, for example "HD Pro Webcam C920 (046d:082d)" or "FaceTime HD Camera". Assign one of them to DeviceName to select that camera.

Browsers only expose device labels after the user has granted camera permission, and devices without a label are skipped. Calling this method before the stream has started may therefore return an empty array.

The call is asynchronous: it returns immediately and callback is invoked on a later round-trip from the client. Use GetDevicesAsync to await the result instead.

Throws:

  • ArgumentNullException Thrown when the callback parameter is null, indicating that a valid callback method must be provided.

Example:

Filling a ComboBox with the available cameras and selecting one:

this.camera.GetDevices(true, deviceNames =>
{
// deviceNames: { "HD Pro Webcam C920 (046d:082d)", "Integrated Webcam", "OBS Virtual Camera" }

this.deviceComboBox.Items.Clear();
this.deviceComboBox.Items.AddRange(deviceNames);

if (deviceNames.Length > 0)
this.camera.DeviceName = deviceNames[0];
else
AlertBox.Show("No camera detected, or permission has not been granted yet.");
});

See also: GetDevicesAsync, DeviceName

Instance member GetDevicesAsync(refresh)​

Returns the names of the available video devices.

ParameterTypeDescription
refresh optionalBooleanRefreshes the list of devices from the browser. Default is false.

Returns: Task<String[]>. An awaitable Task.

Instance member GetImage(callback)​

Captures the current image from the camera and invokes the specified callback with the captured image as an argument. The callback will receive null if the image capture fails or if no image is available.

ParameterTypeDescription
callbackAction<Image>A delegate that processes the captured Image. This parameter cannot be null.

Throws:

Example:

camera.GetImage(image =>
{
if (image != null)
{
Console.WriteLine("Image captured successfully.");
}
else
{
Console.WriteLine("No image available.");
}
});

Instance member GetImageAsync()​

Asynchronously retrieves the current image captured by the camera.

Returns: Task<Image>. A task representing the asynchronous operation, which, when completed, returns an Image object containing the current image from the camera.

This method can be awaited to obtain the latest image captured by the camera hardware. Ensure that the camera is properly initialized and active before calling this method.

Protected member OnError(e)​

Triggers the Error event, indicating that an error has occurred in the camera component.

ParameterTypeDescription
eCameraErrorEventArgsAn instance of CameraErrorEventArgs containing details about the specific error that occurred.

Example:

camera.OnError(new CameraErrorEventArgs("Camera not found"));

Protected member OnProgress(e)​

Fires the Progress event, reporting how much of the recorded stream has been uploaded.

ParameterTypeDescription
eUploadProgressEventArgsAn instance of UploadProgressEventArgs containing the event data for the upload currently in progress: the number of bytes transferred so far and the total number of bytes to transfer.

This event fires only if there is a handler attached to it. A simple overload of the On[Event] method in a derived class will not be invoked unless there is at least one handler attached to the event, since the progress notification is wired to the client only when the Progress event has subscribers.

The client reports raw byte counts rather than a percentage; calculate the percentage from Loaded and Total as shown below. Progress notifications are sent while the recording started by StartRecording is uploaded, either at the interval requested there or once on StopRecording.

Example:

Displaying the upload progress of a recording in a ProgressBar:

this.camera.Progress += (sender, e) =>
{
int percentage = e.Total > 0
? (int)(e.Loaded * 100 / e.Total)
: 0;

this.progressBar.Value = percentage; // 0 ... 100
this.statusLabel.Text = $"Uploading: {percentage}% ({e.Loaded} of {e.Total} bytes)";
};

Derived controls can override the method instead. Call base.OnProgress(e) so that subscribers still receive the event:

protected override void OnProgress(UploadProgressEventArgs e)
{
base.OnProgress(e);

Application.Log($"Uploaded {e.Loaded} of {e.Total} bytes.");
}

See also: Progress, Uploaded, StartRecording

Protected member OnUploaded(e)​

Triggers the Uploaded event, signaling that a file has been successfully uploaded.

ParameterTypeDescription
eUploadedEventArgsAn instance of UploadedEventArgs containing the details of the uploaded file, including its metadata and any associated information.

This method is called internally when the browser finishes posting the recorded stream, after StopRecording or at each interval specified by StartRecording. Subscribe to the Uploaded event, or override this method in a derived class, to process the uploaded data.

The posted data is available through Files. Each entry exposes the file name assigned by the client, the size of the payload in bytes, and the stream containing the data. When overriding, call base.OnUploaded(e) so that subscribers still receive the event.

Example:

Reading the file name and size from the uploaded recording and saving it to disk:

this.camera.Uploaded += (sender, e) =>
{
var file = e.Files[0];

string fileName = file.FileName; // "recording.webm"
int fileSize = file.ContentLength; // 184320 (180 KB)

string path = Path.Combine(Application.StartupPath, "uploads", fileName);
using (var output = System.IO.File.Create(path))
file.InputStream.CopyTo(output);

AlertBox.Show($"Saved {fileName} ({fileSize / 1024} KB).");
};

The same values are available when overriding the method in a derived control:

protected override void OnUploaded(UploadedEventArgs e)
{
base.OnUploaded(e);

foreach (var file in e.Files)
Application.Log($"Uploaded {file.FileName}, {file.ContentLength} bytes.");
}

See also: Uploaded, StartRecording, StopRecording

Protected member OnWebEvent(e)​

Handles events triggered from the client side. This method processes the provided e event arguments, allowing for custom behavior in response to web events related to the camera extension.

ParameterTypeDescription
eWisejEventArgsThe event arguments encapsulating information about the web event.

Implementing this method allows the customization of event handling for specific camera interactions, such as capturing images or handling device status changes.

Example:

// Example of handling a web event from the camera
OnWebEvent(new WisejEventArgs(/* parameters */));

Protected member OnWebRender(config)​

Renders the client component using the specified configuration settings.

ParameterTypeDescription
configObjectA dynamic object containing configuration options for the rendering process. This can include various properties related to the camera component's behavior and appearance.

Instance member StartRecording(format, bitsPerSecond, updateInterval)​

Initiates the recording of audio and video using the specified parameters.

ParameterTypeDescription
format optionalStringThe MIME type for the video encoding format. For more information on MIME types, see MIME_types.
bitsPerSecond optionalInt32The bitrate for both audio and video in bits per second. This determines the quality of the recording. For additional details, refer to MediaRecorder.
updateInterval optionalInt32The interval at which updates are sent, in seconds. A value of zero indicates that the video will be uploaded only upon calling StopRecording.

It is essential to invoke StopRecording to properly end the recording process.

Instance member StopRecording()​

Stops the recording process of the camera. Once the recording is stopped, the recorded stream is uploaded and made available through the Uploaded event.

This method should be called when you want to finalize the recording session. Make sure to handle the Uploaded event to process the uploaded stream accordingly.

Example:

camera.StopRecording();
camera.Uploaded += (sender, e) =>
{
Console.WriteLine("The recorded stream has been uploaded.");
};

Events​

Instance member Error​

CameraErrorHandler Fired when an error occurs in the camera setup or usage.

Instance member Progress​

UploadProgressEventHandler Fired while the Camera control receives the recording stream being uploaded.

This event fires only if there is an handler attached to it. A simple overload of the On[Event] method in a derived class will not be invoked unless there is at least one handler attached to the event.

Instance member Uploaded​

UploadedEventHandler Fired when the current recording is available for download.

Implements​