1、加载本地图片
/// <summary>
/// 加载本地图片方法
/// </summary>
/// <param name="path">图片路径</param>
/// <returns></returns>
public static Texture GetTexture(string path)
{
if (File.Exists(path))
{
byte[] imgBuff = File.ReadAllBytes(path);
Texture2D texture2D = new Texture2D(1, 1);//默认尺寸是多少都无所谓
texture2D.LoadImage(imgBuff);
return texture2D;
}
else
{
return null;
}
}
2、加载网络图片
/// <summary>
/// 通过http链接获取图片资源
/// </summary>
/// <param name="url">网络资源路径</param>
/// <param name="loadEnd">加载成功后调用的方法</param>
/// <returns></returns>
public static IEnumerator DownSprite(string url, Action<Texture2D> loadEnd, Action loadFails)
{
UnityWebRequest wr = new UnityWebRequest(url);
DownloadHandlerTexture texD1 = new DownloadHandlerTexture(true);
wr.downloadHandler = texD1;
yield return wr.SendWebRequest();
int width = 1920;
int high = 1080;
if (!wr.isNetworkError)//!wr.isNetworkError//UnityWebRequest.Result.ConnectionError== UnityWebRequest.Result.Success
{
Texture2D tex = new Texture2D(width, high);
tex = texD1.texture;
loadEnd?.Invoke(tex);
保存本地
//Byte[] bytes = tex.EncodeToPNG();
//File.WriteAllBytes(Application.dataPath + "/Pictures" + "/"+$"{System.DateTime.Now:yyyy-MM-dd_HH-mm-ss}-PlotPointTexture" + ".png", bytes);//"/02.png"
}
else
{
loadFails?.Invoke();
}
}