ImageLoader.cs 2.99 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"); // 万一 URL 空,防止报错

        // 取最后一个 "/" 后面的部分
        string fileName = Path.GetFileName(url);

        // 可能带参数?比如 xxx.jpg?abc=123,去掉参数
        int index = fileName.IndexOf("?", StringComparison.Ordinal);
        if (index >= 0)
        {
            fileName = fileName.Substring(0, index);
        }

        // 防止奇怪 URL 没扩展名,补个默认
        if (string.IsNullOrEmpty(Path.GetExtension(fileName)))
        {
            fileName += ".png"; // 默认 .png
        }

        return fileName;
    }

}