调用笔记本相机进行拍照
根据需求自己去找对应的 组件对号入座
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();
}
}
}