1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| using System.Collections; using System; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; using UnityEngine.Networking;
public class WebCam : MonoBehaviour { WebCamTexture WebTexture; public Image CamImage; public MeshRenderer meshRender; public Button StartUpload; public InputField UrlInput; public string JsonUrl = "/GetPosForm"; public string FileUrl = "/GetFileForm"; private byte[] PNGImage; void Start() { StartCoroutine(OpenCamera()); StartUpload.onClick.AddListener(Upload); UrlInput.text = "http://192.168.50.148:3000"; }
void Update() { }
IEnumerator OpenCamera() { yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); if (Application.HasUserAuthorization(UserAuthorization.WebCam)) { WebCamDevice[] devices = WebCamTexture.devices; string deviceName = devices[0].name; WebTexture = new WebCamTexture(deviceName,1920,1080,60); meshRender.material.mainTexture = WebTexture; WebTexture.Play(); } }
IEnumerator SaveImage(WebCamTexture Image) { Texture2D Texture2DPic = new Texture2D(Image.width, Image.height, TextureFormat.ARGB32, true); Texture2DPic.SetPixels(Image.GetPixels()); Texture2DPic.Apply(); PNGImage = Texture2DPic.EncodeToPNG(); yield return StartCoroutine(UploadFile()); }
public void Upload() { StartCoroutine(SaveImage(WebTexture)); } IEnumerator UploadJson() { Debug.Log("Begin upload Json ..."); WWWForm form = new WWWForm(); form.AddField("Test",123); string Url = UrlInput.text + JsonUrl; using (UnityWebRequest www = UnityWebRequest.Post(Url, form)) { yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError) { Debug.Log(www.error); } else { string text = www.downloadHandler.text; Debug.Log("服务器返回值" + text); } } } IEnumerator UploadFile() { Debug.Log("Being upload file"); WWWForm form = new WWWForm(); form.AddBinaryData("file",PNGImage,GetTimeOfDay() + ".PNG"); string Url = UrlInput.text + FileUrl; Debug.Log(Url); using (UnityWebRequest www = UnityWebRequest.Post(Url, form)) { yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError) { Debug.Log(www.error); } else { string text = www.downloadHandler.text; Debug.Log("服务器返回值" + text); } } }
public string GetTimeOfDay() { var hour = DateTime.Now.Hour; var minute = DateTime.Now.Minute; var second = DateTime.Now.Second; var year = DateTime.Now.Year; var month = DateTime.Now.Month; var day = DateTime.Now.Day; return string.Format("{0:D2}:{1:D2}:{2:D2}_" + "{3:D4}_{4:D2}_{5:D2}", hour, minute, second, year, month, day); } }
|