RemoveBGManager.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using UnityEngine.Events;
  6. using UnityEngine.Networking;
  7. using ToneTuneToolkit.Common;
  8. public class RemoveBGManager : SingletonMaster<RemoveBGManager>
  9. {
  10. public static UnityAction<Texture2D, int> OnRemoveBGFinished;
  11. private const string REMOVEBGAPIURL = "https://api.remove.bg/v1.0/removebg";
  12. private const string APIKEY = "76YHaSA8WZYmbZXfqfBeYbqy";
  13. // ==================================================
  14. [SerializeField] private Texture2D t2dOrigin;
  15. [SerializeField] private Texture2D t2dResult;
  16. [SerializeField] private int flag;
  17. public void UpdatePackage(Texture2D value, int flagValue)
  18. {
  19. t2dOrigin = value;
  20. flag = flagValue;
  21. return;
  22. }
  23. // ==================================================
  24. /// <summary>
  25. /// 上传照片至RemoveBG
  26. /// </summary>
  27. public void StartRemoveBG() => StartCoroutine(nameof(RemoveBGAction));
  28. private IEnumerator RemoveBGAction()
  29. {
  30. WWWForm wwwForm = new WWWForm();
  31. wwwForm.AddBinaryData("image_file", t2dOrigin.EncodeToPNG());
  32. wwwForm.AddField("size", "full");
  33. wwwForm.AddField("type", "person");
  34. wwwForm.AddField("format", "png");
  35. using (UnityWebRequest uwr = UnityWebRequest.Post(REMOVEBGAPIURL, wwwForm))
  36. {
  37. uwr.SetRequestHeader("X-Api-Key", APIKEY);
  38. yield return uwr.SendWebRequest();
  39. if (uwr.result != UnityWebRequest.Result.Success)
  40. {
  41. Debug.LogError(@$"[RBGM] {uwr.error}");
  42. Debug.LogError(@$"[RBGM] {uwr.downloadHandler.text}");
  43. yield break;
  44. }
  45. try
  46. {
  47. Debug.Log(uwr.downloadHandler.data);
  48. Debug.Log(uwr.downloadHandler.data.Length);
  49. byte[] bytes = uwr.downloadHandler.data;
  50. Texture2D t2d = new Texture2D(2, 2);
  51. t2d.LoadImage(bytes);
  52. t2dResult = t2d;
  53. if (OnRemoveBGFinished != null)
  54. {
  55. OnRemoveBGFinished(t2d, flag);
  56. }
  57. }
  58. catch { }
  59. }
  60. yield break;
  61. }
  62. // ==================================================
  63. // 数据类
  64. private ResultJson resultJson;
  65. [Serializable]
  66. public class ResultJson
  67. {
  68. public ResultDataJson data;
  69. }
  70. [Serializable]
  71. public class ResultDataJson
  72. {
  73. public string result_b64;
  74. public int foreground_top;
  75. public int foreground_left;
  76. public int foreground_width;
  77. public int foreground_height;
  78. }
  79. }