ImageLoader.cs
2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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;
}
}