using System.IO;using System.Threading.Tasks;using UnityEngine;using UnityEngine.Experimental.Rendering;using UnityEngine.Networking;namespace Mx.Utils{ /// summary图像工具类/summary public class ImagesUtil { /// summary加载图片/su
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Networking;
namespace Mx.Utils
{
/// <summary>图像工具类</summary>
public class ImagesUtil
{
/// <summary>加载图片</summary>
public static async Task<Texture2D> LoadImageAsync(string path)
{
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(path))
{
var asyncOperation = www.SendWebRequest();
while (!asyncOperation.isDone)
{
await Task.Delay(100);
}
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Failed to load image: " + www.error);
return null;
}
return DownloadHandlerTexture.GetContent(www);
}
}
/// <summary>写入图片</summary>
public static async Task WriteImageAsync(string filePath, Texture2D texture2D)
{
if (texture2D == null) return;
GraphicsFormat graphicsFormat = GraphicsFormat.R8G8B8A8_UNorm;
uint width = (uint)texture2D.width;
uint height = (uint)texture2D.height;
Color32[] array = texture2D.GetPixels32();
await Task.Run(() =>
{
File.WriteAllBytes(filePath, ImageConversion.EncodeArrayToPNG(array, graphicsFormat, width, height));
});
}
}
}