unity在制作很多大屏互动时候都会用到摄像头拍照或者保存图片,摄像头拍照方式也有多种,仅记录一下。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class CameraTest : MonoBehaviour
{
//摄像头图像类,继承自texture
WebCamTexture tex;
public Image WebCam;
public MeshRenderer ma;
public Button saveImage;
public RawImage bgimage_02;
// public RawImage bgimage_03;
int i;
void Start()
{
//开启协程,获取摄像头图像数据
StartCoroutine(OpenCamera());
saveImage.onClick.AddListener(SaveImage);
}
// Update is called once per frame
void Update()
{
}
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.material.mainTexture = tex;
//开始实施获取
tex.Play();
}
}
private void SaveImage()
{
//在上一段代码中加入该方法
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();
}
}
//返回按钮
public void Back()
{
StopCamera();
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}