using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class LoadImage : MonoBehaviour
{
public static LoadImage instance;
/// <summary>
/// 本项目文件夹下的Pictrue地址
/// </summary>
public string FilePath = Directory.GetCurrentDirectory() + @"/Pictrue/";
/// <summary>
/// 本地是否存在照片
/// </summary>
public bool isImgExist;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Destroy(this);
}
}
/// <summary>
/// 网络地址加载图片
/// </summary>
/// <param name="url">地址</param>
/// <param name="raw">图片显示位置</param>
public void loadImage(string url, RawImage raw)
{
if (url == null || url == "")
{
Debug.Log("网址为空!头像是显示默认");
return;
}
if (!IsValidUrl(url))
{
Debug.Log("网址不对,无法下载头像:" + url);
return;
}
string imageName = GetImageName(url);
string myUrl = FilePath + imageName + ".png";
isImgExist = File.Exists(url);
if (isImgExist)
{
StartCoroutine(startLoad(myUrl, imageName, raw));
}
else
{
StartCoroutine(startLoad(url, imageName, raw));
}
}
/// <summary>
/// 加载图片
/// </summary>
/// <param name="url">图片地址</param>
/// <param name="name">唯一不重复变量</param>
/// <param name="raw">图片显示位置</param>
/// <returns></returns>
IEnumerator startLoad(string url, string name, RawImage raw)
{
//加载图片
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(url))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(www.error);
}
else
{
/*这里把贴图转换的过程放到了后台线程来完成,
并且相比于直接脚本加载图片做了优化,减少了内存分配*/
Debug.Log(www);
Texture2D tx = DownloadHandlerTexture.GetContent(www);
raw.texture = tx;
//raw.GetComponent<RectTransform>().sizeDelta = new Vector2(imageWidth, (tx.height * 1.0f / tx.width) * imageWidth);
//图片保存到本地
if (!isImgExist)
{
Byte[] bytes = tx.EncodeToPNG();
File.WriteAllBytes(FilePath + "\\" + name + ".png", bytes);
}
}
}
}
/// <summary>
/// 判断网址对不对
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool IsValidUrl(string url)
{
string pattern = @"^(http|https):\/\/([a-zA-Z0-9]+[-\.]?)+(:[0-9]{1,5})?(\/.*)?$";
return System.Text.RegularExpressions.Regex.Match(url, pattern).Success;
}
/// <summary>
/// 从网址中获取名图片名字
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string GetImageName(string url)
{
int lastSlashIndex = url.LastIndexOf('/');
string str = url.Substring(lastSlashIndex); // 通过Substring()函数删除最后一个'/'之前的部分
//Debug.Log(" 通过Substring()函数删除:"+ str);
int lastSuffixIndex = str.LastIndexOf('.');//删除后缀
str = str.Remove(lastSuffixIndex, str.Length - lastSuffixIndex);
return str;
}
}