unity接本地摄像头

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Test : MonoBehaviour {
    public string devicename;
    WebCamTexture tex;
	
    IEnumerator test()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授权
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            devicename = devices[0].name;
            //设置相机区域
            tex = new WebCamTexture(devicename, 800, 640, 12);
            tex.Play();//开始摄像
        }
    }
    private void OnGUI()
    {
        //开始按钮
        if (GUI.Button(new Rect(0, 0, 100, 100), "click"))
        {
            
                //调用摄像头
                StartCoroutine(test());
            
            
        }
        //暂停按钮
        if (GUI.Button(new Rect(0, 200, 100, 30), "pause"))
        {
            tex.Pause();
        }
        //重新开始按钮
        if (GUI.Button(new Rect(0, 300, 100, 30), "restart"))
        {
            //调用摄像头
            tex.Play();
        }
        //开始按钮
        if (GUI.Button(new Rect(100, 0, 100, 30), "摄像"))
        {
            //开始摄像 摄像就是一系列图片集合
            //开始摄像
            StartCoroutine(getTexture2d());
        }
        if (tex != null)
        {
            GUI.DrawTexture(new Rect(400, 400, 600, 540), tex);
        }
    }
    IEnumerator getTexture2d()
    {
        yield return new WaitForEndOfFrame();
        Texture2D t = new Texture2D(200, 180);//要保存图片的大小
        //街区的区域
        t.ReadPixels(new Rect(200, 320, 200, 180), 0, 0, false);
        t.Apply();
        //把图片数据转化成bytes数组
        byte[] byt = t.EncodeToPNG();
        //然后保存为图片
        File.WriteAllBytes(Application.dataPath + "/shexiang/" + Time.deltaTime + ".jpg", byt);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值