Unity调用笔记本相机进行拍照

该代码示例展示了如何在Unity中调用笔记本相机进行拍照,使用WebCamTexture获取摄像头图像,然后将图像保存为JPG文件。同时,它还涉及到UI组件如RawImage和Button的交互,以及文件系统的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

调用笔记本相机进行拍照


根据需求自己去找对应的 组件对号入座
RawImage image button

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

public class TestDome01SaveImage : MonoBehaviour
{
WebCamTexture tex;

public Image webcam;
public RawImage ma;
public Button SaveButton;
public RawImage bgimage_02;
int i;
// Start is called before the first frame update
void Start()
{
   StartCoroutine(opencamera());
    SaveButton.onClick.AddListener(SaveImage1);
}
IEnumerator opencamera()
{
    yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
    if (Application.HasUserAuthorization(UserAuthorization.WebCam))
    {
        //先获取设备
        WebCamDevice[] device = WebCamTexture.devices;
        string deviceName = device[0].name;
        //然后获取图像
        tex = new WebCamTexture(deviceName);
        //将获取的图像赋值 
        ma.texture = tex;
        //开始实施获取
        tex.Play();
    }
}
private void SaveImage1()
{
    //在上一段代码中加入该方法
    Save(tex);
    i += 1;
}
public void Save(WebCamTexture t)
{
    Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, true);
    //将WebCamTexture 的像素保存到texture2D中
    t2d.SetPixels(t.GetPixels());
    //t2d.ReadPixels(new Rect(200,200,200,200),0,0,false);
    t2d.Apply();
    //编码
    byte[] imageTytes = t2d.EncodeToJPG();
    //if (i % 2 == 1)
    //{
    //   bgimage_02.texture= t2d;
    //}
    //else
    //{
    //    bgimage_03.texture = t2d;
    //}
    bgimage_02.texture = t2d;
    //存储
    File.WriteAllBytes(Application.streamingAssetsPath + "/my/" + Time.time + ".jpg", imageTytes);
}
void StopCamera()
{
    //等待用户允许访问
    //Application.RequestUserAuthorization(UserAuthorization.WebCam);
    //如果用户允许访问,开始获取图像        
    if (Application.HasUserAuthorization(UserAuthorization.WebCam))
    {
        //先获取设备
        WebCamDevice[] device = WebCamTexture.devices;
        string deviceName = device[0].name;
        //然后获取图像
        //  tex = new WebCamTexture(deviceName);
        //  //将获取的图像赋值
        // ma.material.mainTexture = tex;
        //开始实施获取
        tex.Stop();
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值