RemoveBGManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System;
  5. using System.IO;
  6. using Best.HTTP;
  7. using Best.HTTP.Request.Upload.Forms;
  8. using UnityEngine.Events;
  9. using ToneTuneToolkit.Data;
  10. using UnityEngine.Networking;
  11. using System.Text;
  12. namespace LonginesYogaPhotoJoy
  13. {
  14. public class RemoveBGManager : MonoBehaviour
  15. {
  16. public static RemoveBGManager Instance;
  17. private UnityAction<Texture2D> onRemoveBGCompelete;
  18. private const string removebgAPI = "https://api.remove.bg/v1.0/removebg";
  19. // private const string removebgAPI = "http://192.168.50.130:3500";
  20. private string key;
  21. // 测试key U1j4pJeg9zT63Kfa8zDmiRkG
  22. // 正式key 76YHaSA8WZYmbZXfqfBeYbqy // 20240606 剩余100
  23. // live X859F9v3g4YpoPBRQe2n7h8T
  24. [Header("DEBUG - Peek")]
  25. [SerializeField] private Texture2D preuploadTexture;
  26. [SerializeField] private Texture2D downloadTexture;
  27. // ==================================================
  28. private void Awake()
  29. {
  30. Instance = this;
  31. }
  32. private void Start()
  33. {
  34. Init();
  35. }
  36. // ==================================================
  37. public void AddEventListener(UnityAction<Texture2D> unityAction)
  38. {
  39. onRemoveBGCompelete += unityAction;
  40. return;
  41. }
  42. public void RemoveEventListener(UnityAction<Texture2D> unityAction)
  43. {
  44. onRemoveBGCompelete -= unityAction;
  45. return;
  46. }
  47. // ==================================================
  48. private void Init()
  49. {
  50. key = JsonManager.GetJson(Application.streamingAssetsPath + "/removebgkey.json", "Key");
  51. return;
  52. }
  53. // ==================================================
  54. // public void UploadPhoto2RemoveBG(Texture2D value)
  55. // {
  56. // StartCoroutine(UploadPhoto2RemoveBGAction(value));
  57. // return;
  58. // }
  59. // private IEnumerator UploadPhoto2RemoveBGAction(Texture2D value)
  60. // {
  61. // yield return new WaitForEndOfFrame();
  62. // byte[] bytes = value.EncodeToPNG(); // 图转比特流
  63. // // string base64 = "data:image/jpg;base64," + Convert.ToBase64String(bytes);
  64. // WWWForm form = new WWWForm();
  65. // form.AddBinaryData("image_file", bytes);
  66. // form.AddField("size", "auto");
  67. // form.AddField("type", "person");
  68. // using (UnityWebRequest www = UnityWebRequest.Post(removebgAPI, form))
  69. // {
  70. // www.SetRequestHeader("Content-Type", "multipart/form-data");
  71. // // www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  72. // www.SetRequestHeader("X-Api-Key", key);
  73. // DownloadHandler downloadHandler = new DownloadHandlerBuffer();
  74. // www.downloadHandler = downloadHandler;
  75. // yield return www.SendWebRequest();
  76. // if (www.result != UnityWebRequest.Result.Success)
  77. // {
  78. // Debug.Log(www.error + "...<color=red>[ER]</color>");
  79. // yield break;
  80. // }
  81. // else
  82. // {
  83. // result = www.downloadHandler.text.ToString();
  84. // Debug.Log("RemoveBG...<color=green>[OK]</color>");
  85. // // Debug.Log(result + "...<color=green>[OK]</color>");
  86. // }
  87. // }
  88. // }
  89. // public void UploadPhoto2RemoveBG(Texture2D value)
  90. // {
  91. // StartCoroutine(UploadPhoto2RemoveBGAction(value));
  92. // return;
  93. // }
  94. public void UploadPhoto2RemoveBG(Texture2D value)
  95. {
  96. preuploadTexture = value;
  97. byte[] bytes = value.EncodeToJPG(); // 图转比特流
  98. MultipartFormDataStream form = new MultipartFormDataStream();
  99. form.AddStreamField("image_file", new MemoryStream(bytes), "filename", "image/jpg");
  100. form.AddField("size", "auto");
  101. form.AddField("type", "person");
  102. HTTPRequest request = HTTPRequest.CreatePost(new Uri(removebgAPI), RequestFinishedCallback);
  103. request.SetHeader("X-Api-Key", key);
  104. request.UploadSettings.UploadStream = form;
  105. request.Send();
  106. return;
  107. }
  108. private void RequestFinishedCallback(HTTPRequest req, HTTPResponse resp)
  109. {
  110. switch (req.State)
  111. {
  112. case HTTPRequestStates.Finished:
  113. if (resp.IsSuccess)
  114. {
  115. if (onRemoveBGCompelete != null)
  116. {
  117. onRemoveBGCompelete(resp.DataAsTexture2D);
  118. }
  119. Debug.Log("Upload finished succesfully!");
  120. }
  121. else
  122. {
  123. // 6. Error handling
  124. Debug.LogError($"Server sent an error: {resp.StatusCode}-{resp.Message}");
  125. }
  126. break;
  127. // 6. Error handling
  128. default:
  129. Debug.LogError($"Request finished with error! Request state: {req.State}");
  130. break;
  131. }
  132. }
  133. #region 可用
  134. // /// <summary>
  135. // /// 上传照片至RemoveBG
  136. // /// </summary>
  137. // /// <param name="value"></param>
  138. // public void UploadPhoto2RemoveBG(Texture2D value)
  139. // {
  140. // preuploadTexture = value;
  141. // byte[] bytes = value.EncodeToPNG();
  142. // MultipartFormDataStream form = new MultipartFormDataStream();
  143. // form.AddField("image_file", bytes);
  144. // // form.AddField("size", "full");
  145. // form.AddField("size", "auto");
  146. // form.AddField("type", "person");
  147. // HTTPRequest request = new HTTPRequest(
  148. // new Uri(removebgAPI),
  149. // HTTPMethods.Post,
  150. // UploadPictureCallback);
  151. // request.SetHeader("X-Api-Key", key);
  152. // // request.SetForm(form);
  153. // request.UploadSettings.UploadStream = form;
  154. // request.Send();
  155. // return;
  156. // }
  157. // private void UploadPictureCallback(HTTPRequest httpRequest, HTTPResponse httpResponse)
  158. // {
  159. // Debug.Log(httpResponse.StatusCode);
  160. // if (httpResponse == null)
  161. // {
  162. // Debug.Log("RemoveBG请求无响应...<color=red>[ER]</color>");
  163. // return;
  164. // }
  165. // if (httpResponse.StatusCode == 200)
  166. // {
  167. // Debug.Log(httpResponse.DataAsTexture2D.width + " / " + httpResponse.DataAsTexture2D.height);
  168. // string fullPath = $"{Application.streamingAssetsPath}/RemoveBG/{DateTime.Now:yyyy-MM-dd-HH-mm-ss}.png";
  169. // byte[] bytes = httpResponse.DataAsTexture2D.EncodeToPNG();
  170. // File.WriteAllBytes(fullPath, bytes);
  171. // downloadTexture = httpResponse.DataAsTexture2D; // 无必要
  172. // if (onRemoveBGCompelete != null)
  173. // {
  174. // onRemoveBGCompelete(httpResponse.DataAsTexture2D);
  175. // }
  176. // Debug.Log("RemoveBG返回成功...[OK]");
  177. // }
  178. // else
  179. // {
  180. // Debug.Log($"RemoveBG返回失败,{httpResponse.StatusCode}...<color=red>[ER]</color>");
  181. // Debug.Log(httpResponse.DataAsText);
  182. // // UploadPhoto2RemoveBG(preuoloadTexture);
  183. // }
  184. // return;
  185. // }
  186. #endregion
  187. }
  188. }