话不多说。直接上代码
面板我这里使用的事是rawimage
拍摄前后摄像头之前一定要调用stop
有任何问题可以添加 QQ群 207019099
public string deviceName;
//接收返回的图片数据
public WebCamTexture tex;
public Texture2D _tex;
RawImage webrawimage;
void OnGUI()
{
if (tex != null)
{
webrawimage.texture = tex;
}
}
/// <summary>
/// 捕获窗口位置
/// </summary>
/// <param name="webimage"> 图片</param>
/// <param name="chooseimage">选择的图片</param>
/// <param name="isOK">前后摄像头</param>
/// <returns></returns>
public IEnumerator StartCamera(RawImage webimage, RawImage chooseimage, bool isOK)
{
webrawimage = webimage;
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (tex == null)
tex = new WebCamTexture();
WebCamDevice[] devices = WebCamTexture.devices;
for (int i = 0; i < WebCamTexture.devices.Length; i++)
{
//如果是前置摄像机
if (WebCamTexture.devices[i].isFrontFacing && isOK)
{
tex.deviceName = WebCamTexture.devices[i].name;
break;
}
//如果是后置摄像机
else if (!WebCamTexture.devices[i].isFrontFacing && !isOK)
{
tex.deviceName = WebCamTexture.devices[i].name;
break;
}
}
tex.Play();
}
}
///停止拍照
public void StopCamera()
{
if (tex !=null)
tex.Stop();
}
/// <summary>
/// 获取截图
/// </summary>
/// <returns>The texture.</returns>
public IEnumerator GetTexture(Action<Texture2D, byte[]> act)
{
yield return new WaitForEndOfFrame();
Texture2D t = new Texture2D(tex.height, tex.width);// 旋转90度
for (int i = 0; i < tex.height; i++)
for (int j = 0; j < tex.width; j++)
{
t.SetPixel(i, j, tex.GetPixel(j, i));
}
//t.SetPixels(tex.GetPixels());
t.Apply();
byte[] byt = t.EncodeToPNG();
tex.Play();
act(t, byt);
}
/// <summary>
/// 连续捕获照片
/// </summary>
/// <returns>The photoes.</returns>
public IEnumerator SeriousPhotoes()
{
while (true)
{
yield return new WaitForEndOfFrame();
Texture2D t = new Texture2D(400, 300, TextureFormat.RGB24, true);
t.ReadPixels(new Rect(Screen.width / 2 - 180, Screen.height / 2 - 50, 360, 300), 0, 0, false);
t.Apply();
print(t);
byte[] byt = t.EncodeToPNG();
// File.WriteAllBytes(Application.dataPath + "/MulPhotoes/" + Time.time.ToString().Split('.')[0] + "_" + Time.time.ToString().Split('.')[1] + ".png", byt);
Thread.Sleep(300);
}
}