Camera摄像头---拍照---签名---打印---保存

(1)启用摄像头

效果图:
在这里插入图片描述
代码如下:

/// <summary>
/// 摄像头
/// </summary>
public class UsingCamera : MonoBehaviour
{
    public RawImage raw;
    WebCamTexture camTexture;

    void Start()
    {
        StartCoroutine(CallCamera());
    }

    //启用摄像头
    IEnumerator CallCamera()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        try
        {
            if (Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                WebCamDevice[] devices = WebCamTexture.devices; print(devices.Length);
                if (devices.Length == 0)
                {
                    Debug.Log($"WebError:\n未启用摄像头");
                    yield break;
                }
                string deviceName = devices[0].name;
                print(deviceName);
                camTexture = new WebCamTexture(deviceName, 800, 800, 12);
                raw.texture = camTexture;
                camTexture.Play();

            }
        }
        catch
        {
            Debug.Log($"WebError:\n未启用摄像头");
        }
    }
}

程序猫到此一游

(2)2021.6.2拍照

    Texture2D t2dSave = null;
   /// <summary>
   /// 摄像头拍照
   /// </summary>
    public void Capture()
    {
        print("拍照");
        t2dSave = null;
        if (!camTexture || !camTexture.isPlaying) return;
        t2dSave = new Texture2D(camTexture.width, camTexture.height);
        t2dSave.SetPixels(camTexture.GetPixels());
        t2dSave.Apply();

        //camTexture.Stop();//Cannot get pixels when webcam is not running
        camTexture.Pause();
    }

Cannot get pixels when webcam is not running
保存图片的时候摄像头一定要属于运行状态哦!
在这里插入图片描述

   /// <summary>
   /// 保存
   /// </summary>
    public void Save(WebCamTexture t)
    {
        Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, false);
        //将WebCamTexture 的像素保存到texture2D中
        t2d.SetPixels(t.GetPixels());
        t2d.Apply();
        //编码
        byte[] imageTytes = t2d.EncodeToJPG();
        raws.texture = t2d;
        //存储
        File.WriteAllBytes(Application.streamingAssetsPath + "/头像/" + Time.time + ".jpg", imageTytes);
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();//刷新Unity的资产目录
#endif
    }
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值