Unity调用摄像头并截图

首先界面是这样的,很简易,脚本上挂了三个按钮
在这里插入图片描述

直接上代码

using UnityEngine;
using UnityEngine.UI;

public class WebCamera : MonoBehaviour
{
    WebCamTexture camTexture;

    private WebCamDevice[] devices;

    /// <summary>
    /// 摄像头设备名
    /// </summary>
    string deviceName;

    /// <summary>
    /// 摄像头显示状态
    /// </summary>
    bool cameraIsOpen;

    public Button openCamera, closeCamera, screenShot;

    private void Awake()
    {
        //初始化摄像头显示的图像的大小
        camTexture = new WebCamTexture(deviceName, 800, 600, 60);
    }
    private void Start()
    {
        cameraIsOpen = false;
        openCamera.onClick.AddListener(OpenWebCamDevice);
        closeCamera.onClick.AddListener(CloseWebCamDevice);
        screenShot.onClick.AddListener(() =>
        {
            // 将图像传给截图方法
            if (camTexture.isPlaying)
                GetComponent<ScreenShot>().SaveScreenShot(camTexture);
        });
    }


    //通过GUI绘制摄像头要显示的窗口
    private void OnGUI()
    {
        //首先根据摄像头展示的画面来判断摄像头是否存在
        if (cameraIsOpen && camTexture)
        {
            //绘制画面(Screen.width / 2 - 150f, Screen.height / 2 - 290,这里是画面距离场景的高和宽的限制)
            //800, 600是和camTexture的画面一样大的绘制窗口
            GUI.DrawTexture(new Rect(0, 0, 800, 600), camTexture);
        }
        if (!cameraIsOpen && camTexture)//不显示画面(没写这个步骤之前有个坑)
        {
            GUI.DrawTexture(new Rect(Screen.width / 2 - 150f, Screen.height / 2 - 290, 0, 0), camTexture);
        }
    }

    /// <summary>
    /// 打开摄像头
    /// </summary>
    void OpenWebCamDevice()
    {
        //用户授权
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            //显示画面的设备就是要打开的摄像头
            devices = WebCamTexture.devices;
            //获取到设备名称
            deviceName = devices[0].name;
            //开启摄像头
            camTexture.Play();
            cameraIsOpen = true;
        }
    }

    /// <summary>
    /// 关闭摄像头
    /// </summary>
    void CloseWebCamDevice()
    {
        if (cameraIsOpen == true && camTexture != null)
        {
            cameraIsOpen = false;
            camTexture.Stop();
        }
    }
}

截图脚本

using System;
using System.IO;
using UnityEngine;

public class ScreenShot : MonoBehaviour
{
    readonly string savePath = Application.streamingAssetsPath + "/my"; // 图片保存路径

    public void SaveScreenShot(Texture texture)
    {
        Texture2D jietuTexture = TextureToTexture2D(texture);
        Save(jietuTexture);
    }
    /// <summary>
    /// 保存图片
    /// </summary>
    /// <param name="texture2D"></param>
    void Save(Texture2D texture2D)
    {
        byte[] textureBytes = texture2D.EncodeToPNG();
        string filename = string.Format("IMG_{0}{1}{2}_{3}{4}{5}.jpg", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
        if (!Directory.Exists(savePath))
        {
            Directory.CreateDirectory(savePath);
        }
        Debug.Log("保存路径=====" + savePath + "/" + filename);
        File.WriteAllBytes(savePath + "/" + filename, textureBytes);
        if (File.Exists(savePath + "/" + filename))
            Debug.Log("找到照片");
        else
            Debug.Log("未找到");
    }
    /// <summary>
    /// Texture转换成Texture2D
    /// </summary>
    /// <param name="texture"></param>
    /// <returns></returns>
    private Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);

        return texture2D;
    }
}



效果如图
在这里插入图片描述

截图 上面那张图让我不小心删了…
在这里插入图片描述

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
可以通过 Unity 的 WebCamTexture 类来调用摄像头拍照。以下是一个简单的示例代码: ``` using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { private WebCamTexture webcamTexture; // Start is called before the first frame update void Start() { // 获取摄像头设备 WebCamDevice[] devices = WebCamTexture.devices; if (devices.Length == 0) { Debug.Log("No camera detected!"); return; } // 使用第一个摄像头设备 webcamTexture = new WebCamTexture(devices[0].name); // 开始捕捉摄像头画面 webcamTexture.Play(); } // 拍照方法 public void TakePhoto() { // 创建 Texture2D 对象 Texture2D photo = new Texture2D(webcamTexture.width, webcamTexture.height); // 从摄像头捕捉画面到 Texture2D 对象 photo.SetPixels(webcamTexture.GetPixels()); photo.Apply(); // 保存照片到本地 byte[] bytes = photo.EncodeToPNG(); System.IO.File.WriteAllBytes(Application.dataPath + "/photo.png", bytes); } // 在场景中显示摄像头画面 void OnGUI() { if (webcamTexture != null && webcamTexture.isPlaying) { GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), webcamTexture, ScaleMode.ScaleToFit); } } // Stop capturing webcam texture when the script is disabled or destroyed void OnDisable() { if (webcamTexture != null) { webcamTexture.Stop(); } } void OnDestroy() { if (webcamTexture != null) { webcamTexture.Stop(); } } } ``` 在 Start() 方法中,我们获取设备上的摄像头设备,并使用第一个设备。然后通过调用 `WebCamTexture.Play()` 方法开始捕捉摄像头画面。 在 TakePhoto() 方法中,我们创建一个 Texture2D 对象,然后从摄像头捕捉画面到 Texture2D 对象中。最后,我们将照片保存到本地。 在 OnGUI() 方法中,我们通过调用 `GUI.DrawTexture()` 方法来显示摄像头画面。 最后,在 OnDisable() 和 OnDestroy() 方法中,我们停止捕捉摄像头画面。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值