

Maui Blazor 使用摄像头实现 - tokengo
source link: https://www.cnblogs.com/hejiale010426/p/17045707.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Maui Blazor 使用摄像头实现
由于Maui Blazor中界面是由WebView渲染,所以再使用Android的摄像头时无法去获取,因为原生的摄像头需要绑定界面组件
所以我找到了其他的实现方式,通过WebView使用js调用设备摄像头 支持多平台兼容目前测试了Android 和PC 由于没有ioc和mac无法测试 大概率是兼容可能需要动态申请权限
1. 添加js方法
我们再wwwroot中创建一个helper.js
的文件并且添加以下俩个js函数
再index.html
中添加<script src="helper.js"></script>
引入js
/**
* 设置元素的src
* @param {any} canvasId canvasId的dom id
* @param {any} videoId video的dom id
* @param {any} srcId img的dom id
* @param {any} widht 设置截图宽度
* @param {any} height 设置截图高度
*/
function setImgSrc(dest,videoId, srcId, widht, height) {
let video = document.getElementById(videoId);
let canvas = document.getElementById(canvasId);
console.log(video.clientHeight, video.clientWidth);
canvas.getContext('2d').drawImage(video, 0, 0, widht, height);
canvas.toBlob(function (blob) {
var src = document.getElementById(srcId);
src.setAttribute("height", height)
src.setAttribute("width", widht);
src.setAttribute("src", URL.createObjectURL(blob))
}, "image/jpeg", 0.95);
}
/**
* 初始化摄像头
* @param {any} src
*/
function startVideo(src) {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
let video = document.getElementById(src);
if ("srcObject" in video) {
video.srcObject = stream;
} else {
video.src = window.URL.createObjectURL(stream);
}
video.onloadedmetadata = function (e) {
video.play();
};
//mirror image
video.style.webkitTransform = "scaleX(-1)";
video.style.transform = "scaleX(-1)";
});
}
}
然后各个平台的兼容
android:
Platforms/Android/AndroidManifest.xml文件内容
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<!--相机权限-->
<uses-permission android:name="android.permission.CAMERA" android:required="false"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--相机功能-->
<uses-feature android:name="android.hardware.camera" />
<!--音频录制权限-->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!--位置权限-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="http"/>
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https"/>
</intent>
</queries>
</manifest>
Platforms/Android/MainActivity.cs文件内容
[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Platform.Init(this, savedInstanceState);
// 申请所需权限 也可以再使用的时候去申请
ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.Camera, Manifest.Permission.RecordAudio, Manifest.Permission.ModifyAudioSettings }, 0);
}
}
MauiWebChromeClient.cs文件内容
#if ANDROID
using Android.Webkit;
using Microsoft.AspNetCore.Components.WebView.Maui;
namespace MainSample;
public class MauiWebChromeClient : WebChromeClient
{
public override void OnPermissionRequest(PermissionRequest request)
{
request.Grant(request.GetResources());
}
}
public class MauiBlazorWebViewHandler : BlazorWebViewHandler
{
protected override void ConnectHandler(Android.Webkit.WebView platformView)
{
platformView.SetWebChromeClient(new MauiWebChromeClient());
base.ConnectHandler(platformView);
}
}
#endif
在MauiProgram.cs
中添加以下代码;如果没有下面代码会出现没有摄像头权限
具体在这个 issue体现
#if ANDROID
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<IBlazorWebView, MauiBlazorWebViewHandler>();
});
#endif
以上是android的适配代码 pc不需要设置额外代码 ios和mac不清楚
然后编写界面
@page "/" @*界面路由*@
@inject IJSRuntime JSRuntime @*注入jsRuntime*@
@if(OpenCameraStatus) @*在摄像头没有被打开的情况不显示video*@
{
<video id="@VideoId" width="@widht" height="@height" />
<canvas class="d-none" id="@CanvasId" width="@widht" height="@height" />
}
<button @onclick="" style="margin:8px">打开摄像头</button>
@*因为摄像头必须是用户手动触发如果界面是滑动进入无法直接调用方法打开摄像头所以添加按钮触发*@
<button style="margin:8px">截图</button> @*对视频流截取一张图*@
<img id="@ImgId" />
@code{
private string CanvasId;
private string ImgId;
private string VideoId;
private bool OpenCameraStatus;
private int widht = 320;
private int height = 500;
private async Task OpenCamera()
{
if (!OpenCameraStatus)
{
// 由于打开摄像头的条件必须是用户手动触发如果滑动切换到界面是无法触发的
await JSRuntime.InvokeVoidAsync("startVideo", "videoFeed");
OpenCameraStatus = true;
StateHasChanged();
}
}
protected override async Task OnInitializedAsync()
{
// 初始化id
ImgId = Guid.NewGuid().ToString("N");
CanvasId = Guid.NewGuid().ToString("N");
VideoId = Guid.NewGuid().ToString("N");
await base.OnInitializedAsync();
}
private async Task Screenshot()
{
await JSRuntime.InvokeAsync<String>("setImgSrc", CanvasId,VideoId, ImgId, widht, height);
}
}
然后可以运行程序就可以看到我们的效果了
来着token的分享
技术交流群:737776595
本文作者:tokengo
本文链接:https://www.cnblogs.com/hejiale010426/p/17045707.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
Recommend
-
14
如何实现在react现有项目中嵌入Blazor? 目前官方只提供了angular和react俩种示例所以本教程只将react教程 思路讲解: 首先在现有react项目中我们可能某些组件是在Bl...
-
11
目前官方只提供了angular和react俩种示例,所以本教程将来讲解如何在Vue的现有项目中使用,上期已经做好了react的教材! Vue 项目创建流程 ...
-
3
Blazor如何实现类似于微信的Tab切换?
-
9
在 Blazor Hybrid 应用中,Razor 组件在设备上本机运行。 组件通过本地互操作通道呈现到嵌入式 Web View 控件...
-
8
实现创建一个Blazor Server空的应用程序
-
3
本篇博客只实现基本的低代码,比如新增组件,动态修改组件参数 首先创建一个空的Blazor Server,并且命名LowCode.Web 实现我们还需要引用一个Blazor组件库,由于作者用Masa Blazor比较多所以使...
-
8
Photino是什么 Photino是一组使用Web (HTML/CSS/JavaScript)UI创建桌面应用程序的技术。TryPhotino.io 维护 .NET 构建,并鼓励社区开发 Photino.Native 控件以用于其他语言和平台。我们鼓励并将支持Phot...
-
8
.NET 8新预览版本使用 Blazor 组件进行服务器端呈现 ...
-
4
Blazor HyBrid在香橙派(Ubuntu Arm)运行的效果 准备香橙派一块!当前教程使用的是香橙派5 4G开发板
-
9
如何取消Blazor Server烦人的重新连接? 相信很多Blazor的用户在开发内部系统上基本上都选择速度更快,加载更快的Blazor Server模式。 但是Blazor Serve...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK