576 lines
18 KiB
C#
576 lines
18 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.IO;
|
||
using System.Runtime.Serialization;
|
||
using System.Threading.Tasks;
|
||
using Newtonsoft.Json;
|
||
using SixLabors.ImageSharp;
|
||
using SixLabors.ImageSharp.Formats.Png;
|
||
using SixLabors.ImageSharp.Processing;
|
||
using TMPro;
|
||
using Unity.VectorGraphics;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
using UnityEngine.UI;
|
||
using ZXing;
|
||
using ZXing.QrCode;
|
||
using Debug = UnityEngine.Debug;
|
||
using Image = UnityEngine.UI.Image;
|
||
|
||
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();
|
||
|
||
// http://3.109.5.166/api/createTicket
|
||
// https://api.plugcustom.com.cn/kiosk/ImageUpload/create_upload
|
||
using (UnityWebRequest www =
|
||
UnityWebRequest.Post("https://api.plugcustom.com.cn/kiosk/ImageUpload/create_upload", 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<QrcodeResponse>(www.downloadHandler.text);
|
||
//Debug.Log(myDeserializedClass.data.ticket);
|
||
|
||
currentTicket = myDeserializedClass.ticket_id;
|
||
// string link = "http://3.109.5.166/uploadi?ticket=" + myDeserializedClass.upload_url;
|
||
string link = myDeserializedClass.upload_url;
|
||
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 == "")
|
||
{
|
||
yield break;
|
||
}
|
||
|
||
Debug.Log(currentTicket);
|
||
|
||
WWWForm form = new WWWForm();
|
||
// form.AddField("ticket", currentTicket);
|
||
|
||
using (UnityWebRequest www =
|
||
UnityWebRequest.Get(
|
||
$"https://api.plugcustom.com.cn/kiosk/ImageUpload/api/uploads/{currentTicket}/list"))
|
||
{
|
||
yield return www.SendWebRequest();
|
||
|
||
if (www.isNetworkError || www.isHttpError)
|
||
{
|
||
Debug.Log(www.error);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log(www.downloadHandler.text);
|
||
try
|
||
{
|
||
RootObject myDeserializedClass =
|
||
JsonConvert.DeserializeObject<RootObject>(www.downloadHandler.text);
|
||
if (myDeserializedClass.Completed)
|
||
{
|
||
IsUploadSuccess = true;
|
||
StartCoroutine(LoadAllImages(myDeserializedClass.Items));
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
[SerializeField] private GameObject qrcodePage, waitingPage;
|
||
[SerializeField] private Slider slider;
|
||
[SerializeField] private TextMeshProUGUI downloadingProgress;
|
||
|
||
// public PhotobeamerModifyingButton currentBeamerButton;
|
||
// public EditBasketballDesign currentBasketballButton;
|
||
public Action<List<Sprite>> UploadCallbackAction;
|
||
|
||
private IEnumerator LoadAllImages(List<Item> urls)
|
||
{
|
||
slider.value = 0;
|
||
downloadingProgress.text = "";
|
||
waitingPage.SetActive(true);
|
||
qrcodePage.SetActive(false);
|
||
int i = 0;
|
||
currentSprites.Clear();
|
||
|
||
Debug.Log(urls.Count);
|
||
foreach (var url in urls)
|
||
{
|
||
Debug.Log($"url is : {url.Url}");
|
||
downloadingProgress.text = "downloading image " + (i + 1) + "/" + urls.Count;
|
||
yield return StartCoroutine(LoadImageToSprite(url.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<Sprite> currentSprites = new List<Sprite>();
|
||
|
||
private IEnumerator LoadImageToSprite1(string url)
|
||
{
|
||
IsPreviewing = true;
|
||
|
||
using (UnityWebRequest request = UnityWebRequest.Get(url))
|
||
{
|
||
var operation = request.SendWebRequest();
|
||
|
||
while (!operation.isDone)
|
||
{
|
||
slider.value = request.downloadProgress;
|
||
yield return null;
|
||
}
|
||
|
||
if (request.result != UnityWebRequest.Result.Success)
|
||
{
|
||
Debug.LogError("下载错误: " + request.error);
|
||
}
|
||
else
|
||
{
|
||
byte[] imageData = request.downloadHandler.data;
|
||
|
||
Stopwatch sw = new Stopwatch();
|
||
sw.Start();
|
||
// 1. 使用ImageSharp加载图片并自动修正旋转
|
||
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(imageData))
|
||
{
|
||
Stopwatch sw2 = new Stopwatch();
|
||
sw2.Start();
|
||
// 自动应用Exif旋转(核心功能!)
|
||
image.Mutate(x => x.AutoOrient());
|
||
sw2.Stop();
|
||
Debug.Log($"sw2 方法执行时间:{sw2.ElapsedMilliseconds} ms");
|
||
|
||
Stopwatch sw3 = new Stopwatch();
|
||
sw3.Start();
|
||
// 2. 将处理后的图片转换为字节数组
|
||
using (var ms = new System.IO.MemoryStream())
|
||
{
|
||
image.Save(ms, new PngEncoder()); // 保存为PNG格式
|
||
byte[] correctedData = ms.ToArray();
|
||
|
||
// 3. 加载为Unity纹理
|
||
Texture2D texture = new Texture2D(2, 2);
|
||
texture.LoadImage(correctedData);
|
||
|
||
// 4. 转换为Sprite
|
||
Sprite sprite = Sprite.Create(
|
||
texture,
|
||
new Rect(0, 0, texture.width, texture.height),
|
||
new Vector2(0.5f, 0.5f)
|
||
);
|
||
currentSprites.Add(sprite);
|
||
}
|
||
sw3.Stop();
|
||
Debug.Log($"sw3 方法执行时间:{sw3.ElapsedMilliseconds} ms");
|
||
}
|
||
|
||
sw.Stop();
|
||
Debug.Log($"sw 方法执行时间:{sw.ElapsedMilliseconds} ms");
|
||
}
|
||
}
|
||
|
||
IsPreviewing = false;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
|
||
string currentTicket = "";
|
||
|
||
public void ClosePage()
|
||
{
|
||
Debug.Log("closing time");
|
||
Debug.Log(currentTicket);
|
||
|
||
StartCoroutine(DeleteTicket());
|
||
}
|
||
|
||
private IEnumerator DeleteTicket()
|
||
{
|
||
Debug.Log("closing time");
|
||
Debug.Log(currentTicket);
|
||
|
||
if (currentTicket == "")
|
||
{
|
||
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 = "";
|
||
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<string> url { get; set; }
|
||
}
|
||
|
||
public class PhotoResponse
|
||
{
|
||
public bool success { get; set; }
|
||
public bool completed { get; set; }
|
||
|
||
public ImageList items { get; set; }
|
||
|
||
// public List<string> items{ get; set; }
|
||
public string message { get; set; }
|
||
}
|
||
|
||
[DataContract]
|
||
public class Item
|
||
{
|
||
[DataMember(Name = "key")] public string Key { get; set; }
|
||
|
||
[DataMember(Name = "last_modified")] public string LastModified { get; set; }
|
||
|
||
[DataMember(Name = "size")] public long Size { get; set; }
|
||
|
||
[DataMember(Name = "url")] public string Url { get; set; }
|
||
}
|
||
|
||
[DataContract]
|
||
public class RootObject
|
||
{
|
||
[DataMember(Name = "completed")] public bool Completed { get; set; }
|
||
|
||
[DataMember(Name = "count")] public int Count { get; set; }
|
||
|
||
[DataMember(Name = "items")] public List<Item> Items { get; set; }
|
||
|
||
[DataMember(Name = "ts")] public long Ts { get; set; }
|
||
|
||
[DataMember(Name = "upload_id")] public string UploadId { 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; }
|
||
public string ticket_id { get; set; }
|
||
public string upload_url { get; set; }
|
||
}
|
||
|
||
#endregion
|
||
} |