ImageUploader.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Networking;
  6. public class ImageUploader : MonoBehaviour
  7. {
  8. //public GameObject sendingPanel;
  9. public GameObject errorPanel;
  10. public GameObject masterConnector;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. }
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. }
  19. public void UploadImageToServer()
  20. {
  21. //sendingPanel.SetActive(true); //delete sending panel since it block the image in the middle
  22. StartCoroutine( TakeScreenshotAndSave() );
  23. }
  24. private IEnumerator TakeScreenshotAndSave()
  25. {
  26. yield return new WaitForEndOfFrame();
  27. Texture2D ss = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
  28. ss.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 );
  29. ss.Apply();
  30. // SEND THE PHOTO TO SERVER
  31. byte[] bytes = ss.EncodeToPNG();
  32. Debug.Log( "Permission result: sucess");
  33. string gameNumber = masterConnector.GetComponent<MasterCreateGame>().GetGameNumber();
  34. StartCoroutine(SendImageToServer(gameNumber, bytes));
  35. // To avoid memory leaks
  36. Destroy( ss );
  37. }
  38. public IEnumerator SendImageToServer(string gameNumber, byte[] image)
  39. {
  40. string serverUrl = "https://smarthubs.media.tuwien.ac.at/api/add_image_to_game";
  41. // Create a Web Form
  42. WWWForm form = new WWWForm();
  43. form.AddField("game", gameNumber);
  44. form.AddBinaryData("img", image);
  45. using (UnityWebRequest www = UnityWebRequest.Post(serverUrl, form))
  46. {
  47. yield return www.SendWebRequest();
  48. if (www.result != UnityWebRequest.Result.Success)
  49. {
  50. Debug.Log(www.error);
  51. // PROMPT ERROR
  52. errorPanel.SetActive(true);
  53. }
  54. else
  55. {
  56. Debug.Log("Form upload complete!");
  57. //sendingPanel.SetActive(false); //delete sending panel since it block the image in the middle
  58. }
  59. }
  60. }
  61. }