using asap.core; using System.Collections.Generic; using System.Threading.Tasks; using UnityEngine; using UniRx; using System.IO; using System; using System.Net.Http; namespace game { public class GetAvatarDataEvent { public string url; public TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); } public class AvatarService { Dictionary code2Pic = new Dictionary(); public string savePath = Application.persistentDataPath + "/DownloadedImages/"; // 保存到持久化数据路径 public AvatarService() { GContext.OnEvent().Subscribe(SetAsyncImage); } async void SetAsyncImage(GetAvatarDataEvent data) { if (string.IsNullOrEmpty(data.url)) { return; } int code = data.url.GetHashCode(); if (!code2Pic.TryGetValue(code, out Sprite sprite)) { try { sprite = await DownloadImage(data.url, code); } catch (System.Exception e) { Debug.LogError("图片不存在,下载出错:" + e.Message + "====" + data.url); sprite = null; } } data.taskCompletionSource.SetResult(sprite); } Sprite LoadImage(string path) { // 加载图片 Texture2D texture = LoadTextureFromPath(path); // 将Texture转换为Sprite return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); } Texture2D LoadTextureFromPath(string path) { byte[] bytes = File.ReadAllBytes(path); Texture2D texture = new Texture2D(256, 256); texture.LoadImage(bytes); return texture; } async Task DownloadImage(string url, int code) { Sprite m_sprite; if (url.Contains("http")) { // 检查本地是否存在图片 string fullPath = Path.Combine(savePath, code.ToString()); if (File.Exists(fullPath)) { // 在这里加载并使用本地图片 code2Pic[code] = LoadImage(fullPath); } else { using (HttpClient client = new HttpClient()) { try { client.Timeout = TimeSpan.FromSeconds(15); HttpResponseMessage response = await client.GetAsync(url); byte[] imageBytes = await response.Content.ReadAsByteArrayAsync(); if (!code2Pic.ContainsKey(code)) { Texture2D texture = new Texture2D(256, 256); texture.LoadImage(imageBytes); Texture2D tex2d = texture; m_sprite = Sprite.Create(tex2d, new Rect(0, 0, tex2d.width, tex2d.height), new Vector2(0, 0)); code2Pic[code] = m_sprite; } try { // 确保保存路径存在 if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } // 保存纹理为PNG文件 File.WriteAllBytes(fullPath, imageBytes); } catch (Exception ex) { Debug.LogWarning($"保存图片时出错: {ex.Message} +++ {ex.StackTrace}"); } } catch (Exception ex) { Debug.LogWarning($"下载图片时出错: {ex.Message} +++ {ex.StackTrace}"); return null; } } } } else { GetSpriteEvent getSpriteEvent = new GetSpriteEvent(url); GContext.Publish(getSpriteEvent); if (!code2Pic.ContainsKey(code)) { code2Pic[code] = getSpriteEvent.sprite; } } return code2Pic[code]; } } }