EnergyEfficiencyManagement/Assets/SKFramework/Core/FileLoader/LocalImageLoader.cs

93 lines
2.5 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using System.IO;
using UnityEngine;
public static class LocalImageLoader
{
/// <summary>
/// 加载文件夹下的所有图片,返回 Texture2D 列表
/// </summary>
/// <param name="folderPath">图片文件夹完整路径</param>
public static List<Texture2D> LoadImages(string folderPath)
{
List<Texture2D> textures = new List<Texture2D>();
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;
}
/// <summary>
/// 加载单张本地图片
/// </summary>
/// <param name="filePath">图片完整路径</param>
/// <returns>Texture2D失败返回 null</returns>
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";
}
}