using System.Collections.Generic; using System.IO; using UnityEngine; public static class LocalImageLoader { /// /// 加载文件夹下的所有图片,返回 Texture2D 列表 /// /// 图片文件夹完整路径 public static List LoadImages(string folderPath) { List textures = new List(); if (!Directory.Exists(folderPath)) { Debug.LogError($"[LocalImageLoader] 文件夹不存在: {folderPath}"); return textures; } string[] files = Directory.GetFiles(folderPath); foreach (string file in files) { if (!IsImageFile(file)) continue; byte[] data = File.ReadAllBytes(file); Texture2D tex = new Texture2D(2, 2, TextureFormat.RGBA32, false); if (tex.LoadImage(data)) { tex.name = Path.GetFileNameWithoutExtension(file); textures.Add(tex); } else { Object.Destroy(tex); Debug.LogWarning($"图片加载失败: {file}"); } } return textures; } /// /// 加载单张本地图片 /// /// 图片完整路径 /// Texture2D,失败返回 null public static Texture2D LoadImage(string filePath) { if (!File.Exists(filePath)) { Debug.LogError($"[LocalImageLoader] 图片不存在: {filePath}"); return null; } if (!IsImageFile(filePath)) { Debug.LogError($"[LocalImageLoader] 非图片格式: {filePath}"); return null; } try { byte[] data = File.ReadAllBytes(filePath); Texture2D tex = new Texture2D(2, 2, TextureFormat.RGBA32, false); if (!tex.LoadImage(data)) { Object.Destroy(tex); Debug.LogError($"[LocalImageLoader] 图片解析失败: {filePath}"); return null; } tex.name = Path.GetFileNameWithoutExtension(filePath); return tex; } catch (System.Exception e) { Debug.LogError($"[LocalImageLoader] 加载图片异常: {e.Message}"); return null; } } private static bool IsImageFile(string path) { string ext = Path.GetExtension(path).ToLower(); return ext == ".png" || ext == ".jpg" || ext == ".jpeg"; } }