一、开发环境
- 罗技C930e网络摄像头
- Unity2017.3.1f1
- VS Code
二、功能需求
登录模块的人脸识别。
- 调用摄像头拍摄一张照片
- 把上述摄像头转码为base64并根据特定格式组合为一个json字符串
- 上传该字符串到外网服务器
- 接收从外网服务器返回的数据并进行后续的业务处理(比对数据库是否存在该身份证号码)
ps:北京分部的同事怎么还原base64字符串为图片,并解析图片信息暂且不表。
三、代码实现(精华提取,涉及UI部分已去除)
/*
* @Author: ZoJet
* @Date: 2019-06-19 15:55:54
* @Content:
* @Version:
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
public class JsonDatas
{
public string filename;
public string base64;
public string format;
}
public class OCRVerification : MonoBehaviour
{
private WebCamTexture webCamTexture = null;
private Texture2D texture = null;
private string postData = "";
private string serverUrl = "";
private void OnApplicationQuit()
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
}
private IEnumerator GetWebCamTexture()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
if (devices.Length > 0)
{
webCamTexture = new WebCamTexture(devices[0].name, 1920, 1080, 30);
}
}
}
private string Texture2dToBase64()
{
if (texture != null)
{
byte[] bytes = texture.EncodeToPNG();
return Convert.ToBase64String(bytes);
}
return null;
}
private IEnumerator GetTextureDataByWebCam()
{
if (webCamTexture != null)
{
webCamTexture.Pause();
}
yield return new WaitForEndOfFrame();
if (webCamTexture != null)
{
texture = new Texture2D(webCamTexture.requestedWidth, webCamTexture.requestedHeight);
texture.SetPixels(webCamTexture.GetPixels());
texture.Apply();
}
JsonDatas jsonDatas = new JsonDatas();
jsonDatas.filename = "pic";
jsonDatas.base64 = Texture2dToBase64();
jsonDatas.format = ".jpg";
postData = "[" + JsonUtility.ToJson(jsonDatas) + "]";
}
private string GetDataFromServer(string serverUrl, string postData)
{
try
{
byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(postData);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(serverUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
webReq.ContentLength = bytes.Length;
using (Stream newStream = webReq.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
}
using (WebResponse res = webReq.GetResponse())
{
Stream responseStream = res.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
string result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
return result;
}
}
catch
{
}
return "";
}
}