using System; using System.Collections; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using TMPro; using Unity.VectorGraphics; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using ZXing; using ZXing.QrCode; namespace HK.Tool { public class UploadPhotoPage : MonoBehaviour { public static UploadPhotoPage instance; private void Awake() { instance = this; // gameObject.SetActive(false); } private void Start() { // OpenBeamer(); } [SerializeField] private RawImage qrcode; [SerializeField] private GameObject loading; public void OpenBeamer() { gameObject.SetActive(true); qrcode.gameObject.SetActive(false); loading.SetActive(true); //qrcode.texture = generateQR("www.google.com"); qrcodePage.SetActive(true); waitingPage.SetActive(false); StartCoroutine(GetQrcodeLink()); } private static Color32[] Encode(string textForEncoding, int width, int height) { var writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write(textForEncoding); } public Texture2D generateQR(string text) { var encoded = new Texture2D(512, 512); var color32 = Encode(text, encoded.width, encoded.height); encoded.SetPixels32(color32); encoded.Apply(); return encoded; } IEnumerator GetQrcodeLink() { Debug.Log("called"); WWWForm form = new WWWForm(); using (UnityWebRequest www = UnityWebRequest.Post("http://3.109.5.166/api/createTicket", form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); try { QrcodeResponse myDeserializedClass = JsonConvert.DeserializeObject(www.downloadHandler.text); //Debug.Log(myDeserializedClass.data.ticket); currentTicket = myDeserializedClass.data.ticket; string link = "http://3.109.5.166/uploadi?ticket=" + myDeserializedClass.data.ticket; Debug.Log(link); qrcode.texture = generateQR(link); qrcode.gameObject.SetActive(true); loading.SetActive(false); StartCoroutine(LoopCheck()); //StartCoroutine(LoadImageToRawImage(myDeserializedClass.data.qrcode)); } catch { } } } } public void ClearImages() { currentSprites.Clear(); } public void RemoveImageAt(int i) { currentSprites.RemoveAt(i); } bool IsUploadSuccess = false; private IEnumerator LoopCheck() { IsUploadSuccess = false; while (!IsUploadSuccess) { yield return StartCoroutine(DownloadImageCheck()); yield return new WaitForSecondsRealtime(3f); } } private IEnumerator DownloadImageCheck() { if (currentTicket == -1) { yield break; } Debug.Log(currentTicket); WWWForm form = new WWWForm(); form.AddField("ticket", currentTicket); using (UnityWebRequest www = UnityWebRequest.Post("http://3.109.5.166/api/getCustomerPhoto", form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); try { PhotoResponse myDeserializedClass = JsonConvert.DeserializeObject(www.downloadHandler.text); if (myDeserializedClass.success) { IsUploadSuccess = true; StartCoroutine(LoadAllImages(myDeserializedClass.data.url)); } } catch { } } } } [SerializeField] private GameObject qrcodePage, waitingPage; [SerializeField] private Slider slider; [SerializeField] private TextMeshProUGUI downloadingProgress; // public PhotobeamerModifyingButton currentBeamerButton; // public EditBasketballDesign currentBasketballButton; public Action> UploadCallbackAction; private IEnumerator LoadAllImages(List urls) { slider.value = 0; downloadingProgress.text = ""; waitingPage.SetActive(true); qrcodePage.SetActive(false); int i = 0; currentSprites.Clear(); Debug.Log(urls.Count); foreach (string url in urls) { downloadingProgress.text = "downloading image " + (i + 1) + "/" + urls.Count; yield return StartCoroutine(LoadImageToSprite(url)); i++; } Debug.Log(urls.Count); Debug.Log("ok now"); UploadCallbackAction?.Invoke(currentSprites); //Debug.Log(currentBeamerButton); // if (currentBeamerButton) // currentBeamerButton.FillWithSelectedImages(); // else if (currentBasketballButton) // currentBasketballButton.FillWithSelectedImages(); Debug.Log("try to close"); ClosePage(); } [SerializeField] private GameObject previewPage; [SerializeField] private Image[] previewImages; private bool IsPreviewing = false; [SerializeField] private string[] modelsCommand; public void ChooseImage(int i) { IsPreviewing = false; currentSprites.Add(previewImages[i].sprite); previewPage.gameObject.SetActive(false); } public void PutInImages(int i, Sprite sprite) { previewImages[i].gameObject.SetActive(true); previewImages[i].sprite = sprite; } public List currentSprites = new List(); private IEnumerator LoadImageToSprite(string url) { IsPreviewing = true; UnityWebRequest request = UnityWebRequestTexture.GetTexture(url); request.SendWebRequest(); while (!request.isDone) { slider.value = request.downloadProgress; yield return null; } if (request.isNetworkError || request.isHttpError) Debug.Log(request.error); else { Sprite sprite = ToSprite(((DownloadHandlerTexture)request.downloadHandler).texture); if (sprite != null) currentSprites.Add(sprite); /* previewPage.SetActive(true); foreach(var x in previewImages) { x.gameObject.SetActive(false); } Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler).texture; byte[] textureBytes = texture.EncodeToPNG(); Sprite baseImage = ToSprite(texture); PutInImages(0, baseImage); //texture = ((DownloadHandlerTexture)request.downloadHandler).texture; string savePath = "temp/"; //byte[] textureBytes = texture.EncodeToPNG(); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } string fileName = "downloadedTexture.png"; string transferName = "transferTexture.png"; string filePath = Path.Combine(savePath, fileName); string transferPath = Path.Combine(savePath, transferName); File.WriteAllBytes(filePath, textureBytes); int i = 1; foreach (var command in modelsCommand) { Debug.Log($"i {command} {filePath} {transferPath}"); System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo { FileName = "rembg", Arguments = $"i {command} {filePath} {transferPath}", CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; // Run rembg as a separate process System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = psi }; process.Start(); while(!process.HasExited) { yield return null; } if (File.Exists(transferPath)) { // Read the processed texture byte[] processedTextureBytes = File.ReadAllBytes(transferPath); Texture2D processedTexture = new Texture2D(1, 1); processedTexture.LoadImage(processedTextureBytes); Sprite sprite = ToSprite(processedTexture); PutInImages(i, sprite); //currentSprites.Add(sprite); Debug.Log("Texture processed and applied successfully."); } i++; } while (IsPreviewing) { yield return null; } // Check if the directory exists, if not, create it */ } } private Sprite ToSprite(Texture2D tex) { if (tex == null) { Debug.Log("tex is null"); return null; } Debug.Log("width"); Debug.Log(tex?.width); tex.Compress(false); Debug.Log(tex?.width); Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero); return sp; } int currentTicket = -1; public void ClosePage() { Debug.Log("closing time"); Debug.Log(currentTicket); StartCoroutine(DeleteTicket()); } private IEnumerator DeleteTicket() { Debug.Log("closing time"); Debug.Log(currentTicket); if (currentTicket == -1) { gameObject.SetActive(false); yield break; } WWWForm form = new WWWForm(); form.AddField("ticket", currentTicket); using (UnityWebRequest www = UnityWebRequest.Post("http://3.109.5.166/api/deleteTicket", form)) { yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); } currentTicket = -1; gameObject.SetActive(false); } } private IEnumerator LoadImageToRawImage(string url) { Debug.Log(url); UnityWebRequest www = UnityWebRequest.Get(url); yield return www.SendWebRequest(); if (www.isHttpError || www.isNetworkError) { Debug.Log("Error while Receiving: " + www.error); } else { //Convert byte[] data of svg into string string bitString = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data); Debug.Log(bitString); var tessOptions = new VectorUtils.TessellationOptions() { StepDistance = 100.0f, MaxCordDeviation = 0.5f, MaxTanAngleDeviation = 0.1f, SamplingStepSize = 0.01f }; // Dynamically import the SVG data, and tessellate the resulting vector scene. var sceneInfo = SVGParser.ImportSVG(new StringReader(bitString)); var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions); // Build a sprite with the tessellated geometry Sprite sprite = VectorUtils.BuildSprite(geoms, 10.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true); //qrcode.sprite = sprite; } yield return null; } } #region Data public class ImageList { public List url { get; set; } } public class PhotoResponse { public bool success { get; set; } public ImageList data { get; set; } public string message { get; set; } } public class Data { public int ticket { get; set; } public string qrcode { get; set; } } public class QrcodeResponse { public bool success { get; set; } public Data data { get; set; } public string message { get; set; } } #endregion }