Я нашел базовый CameraStarterSDK из Windows и попытался адаптировать его в DLL, но я не понимаю, чего мне не хватает или я неправильно его называю. Powershell выдает следующие ошибки в зависимости от того, как я пытаюсь его импортировать.
Add-type выдает ошибку:
Невозможно загрузить один или несколько запрошенных файлов. типы. Получите свойство LoaderExceptions для получения дополнительной информации.
Reflection Assembly::Loadfile метод с $custObj = New-Object CameraClassLibrary.Camera выдает ошибку:
Невозможно найти тип [CameraClassLibrary.Camera]: убедитесь, что сборка, содержащая этот тип, загружена.
Неправильно ли я собрал DLL? или я неправильно вызываю/использую его в PowerShell?
Код C# DLL
Код: Выделить всё
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
namespace CameraClassLibrary
{
public class Camera
{
private StorageFolder _captureFolder = null;
private MediaCapture _mediaCapture;
private bool _isInitialized;
private bool _isPreviewing;
private bool _isRecording;
private bool _externalCamera;
private async Task InitializeCameraAsync()
{
Debug.WriteLine("InitializeCameraAsync");
if (_mediaCapture == null)
{
// Attempt to get the back camera if one is available, but use any camera device if not
var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
if (cameraDevice == null)
{
Debug.WriteLine("No camera device found!");
return;
}
// Create MediaCapture and its settings
_mediaCapture = new MediaCapture();
// Register for a notification when video recording has reached the maximum time and when something goes wrong
_mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
_mediaCapture.Failed += MediaCapture_Failed;
var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
// Initialize MediaCapture
try
{
await _mediaCapture.InitializeAsync(settings);
_isInitialized = true;
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine("The app was denied access to the camera");
}
// If initialization succeeded, start the preview
if (_isInitialized)
{
// Figure out where the camera is located
if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
{
// No information on the location of the camera, assume it's an external camera, not integrated on the device
_externalCamera = true;
}
else
{
// Camera is fixed on the device
_externalCamera = false;
// Only mirror the preview if the camera is on the front panel
}
}
}
}
private async Task TakePhotoAsync(string Filename)
{
await InitializeCameraAsync();
var stream = new InMemoryRandomAccessStream();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync(Filename + ".jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
//var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file);
Debug.WriteLine("Photo saved!");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
private async Task CleanupCameraAsync()
{
Debug.WriteLine("CleanupCameraAsync");
if (_isInitialized)
{
// If a recording is in progress during cleanup, stop it to save the recording
if (_isRecording)
{
await StopRecordingAsync();
}
_isInitialized = false;
}
if (_mediaCapture != null)
{
_mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded;
_mediaCapture.Failed -= MediaCapture_Failed;
_mediaCapture.Dispose();
_mediaCapture = null;
}
}
private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file)
{
using (var inputStream = stream)
{
var decoder = await BitmapDecoder.CreateAsync(inputStream);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
//var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
//await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
}
}
}
private static async Task FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();
}
private async void MediaCapture_RecordLimitationExceeded(MediaCapture sender)
{
// This is a notification that recording has to stop, and the app is expected to finalize the recording
await StopRecordingAsync();
}
private async void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
{
Debug.WriteLine("MediaCapture_Failed: (0x{0:X}) {1}", errorEventArgs.Code, errorEventArgs.Message);
await CleanupCameraAsync();
}
private async Task StopRecordingAsync()
{
Debug.WriteLine("Stopping recording...");
_isRecording = false;
await _mediaCapture.StopRecordAsync();
Debug.WriteLine("Stopped recording!");
}
public async void TakePhoto(string Filename)
{
await TakePhotoAsync(Filename);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... usb-camera
Мобильная версия