ImageLoader.cs 3.31 KB
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public static class ImageLoader
{
    /// <summary>
    /// 加载图片,支持本地缓存
    /// </summary>
    /// <param name="url">图片地址</param>
    /// <param name="targetImage">目标 Image</param>
    /// <param name="onSizeReady">图片宽高回调</param>
    /// <returns></returns>
    public static IEnumerator LoadImage(string url, Image targetImage, Action<int, int> onSizeReady = null)
    {
        // 生成缓存文件名
        string fileName = GetFileNameFromUrl(url);
        string cachePath = Path.Combine(Application.temporaryCachePath, fileName);

        Texture2D tex = null;

        // 1️⃣ 本地有缓存?
        if (File.Exists(cachePath))
        {
            Debug.Log($"[ImageLoader] 加载本地缓存图片: {cachePath}");

            byte[] fileData = File.ReadAllBytes(cachePath);
            tex = new Texture2D(2, 2); // 临时大小,LoadImage 会自动调整
            tex.LoadImage(fileData);
        }
        else
        {
            // Debug.Log($"[ImageLoader] 下载图片: {url}");

            using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url))
            {
                yield return uwr.SendWebRequest();

                if (uwr.result == UnityWebRequest.Result.Success)
                {
                    tex = DownloadHandlerTexture.GetContent(uwr);

                    // 保存到本地缓存
                    byte[] pngData = tex.EncodeToPNG();
                    File.WriteAllBytes(cachePath, pngData);

                    // Debug.Log($"[ImageLoader] 下载完成,已缓存到: {cachePath}");
                }
                else
                {
                    Debug.LogError($"[ImageLoader] 下载失败: {uwr.error}");
                    yield break;
                }
            }
        }

        // 2️⃣ 应用到 UI
        if (tex != null && targetImage != null)
        {
            targetImage.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(1f, 1f));

            // 回调宽高
            onSizeReady?.Invoke(tex.width, tex.height);
        }
    }

    /// <summary>
    /// 从 URL 生成缓存文件名
    /// </summary>
    private static string GetFileNameFromUrl(string url)
    {
        if (string.IsNullOrEmpty(url))
            return Guid.NewGuid().ToString("N");

        // 拆分路径
        Uri uri = new Uri(url);
        string[] segments = uri.AbsolutePath.Split('/');

        if (segments.Length < 2)
            return Path.GetFileName(url); // fallback

        string folderName = segments[segments.Length - 2]; // 倒数第二段
        string fileName = segments[segments.Length - 1];   // 最后一段

        // 去掉问号参数部分(如果有)
        int index = fileName.IndexOf("?", StringComparison.Ordinal);
        if (index >= 0)
        {
            fileName = fileName.Substring(0, index);
        }

        // 合并文件名(中间用 - 连接)
        string combinedName = $"{folderName}-{fileName}";

        // 确保有扩展名,没有则补 ".png"
        if (string.IsNullOrEmpty(Path.GetExtension(combinedName)))
        {
            combinedName += ".png";
        }

        return combinedName;
    }


}