using System.Collections; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class TextureDownload : MonoBehaviour { public bool SAVE = true; public RectTransform rect; public RawImage texture; public Image imgLoading; public void Download(string path) { StartCoroutine(ImageDownload(path)); } public void Initialized() { texture.texture = null; imgLoading.gameObject.SetActive(false); } private void OnDisable() { Initialized(); } /// /// 이미지를 다운로드 합니다. /// /// /// IEnumerator ImageDownload(string path) { imgLoading.gameObject.SetActive(true); yield return null; string pathSave = $"{Application.temporaryCachePath}/{getMd5Hash(path)}"; //Debugging.Warning($"{pathSave}"); texture.texture = ImageFileLoad(pathSave); if (texture.texture == null) { UnityWebRequest www = UnityWebRequestTexture.GetTexture(path); yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) Debugging.Error($"ImageDownload Error\n{www.error}"); else { texture.texture = DownloadHandlerTexture.GetContent(www); if (SAVE) ImageFileSave(pathSave, DownloadHandlerTexture.GetContent(www)); } } Resize(); imgLoading.gameObject.SetActive(false); } /// /// 문자열의 MD5 를 생성합니다. /// 이미지 다운로드 URL 을 MD5 로 변환하여 파일명으로 사용합니다. /// /// /// string getMd5Hash(string input) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) sBuilder.Append(data[i].ToString("x2")); return sBuilder.ToString(); } /// /// 다운로드 완료한 이미지를 로컬에 저장합니다. /// /// /// void ImageFileSave(string path, Texture2D texture) { Texture2D newTexture = new Texture2D(texture.width, texture.height); newTexture.SetPixels(0, 0, texture.width, texture.height, texture.GetPixels()); newTexture.Apply(); byte[] bytes = newTexture.EncodeToPNG(); File.WriteAllBytes(path, bytes); } /// /// 로컬에서 이미지를 불러옵니다. /// /// /// Texture ImageFileLoad(string path) { FileInfo fileInfo = new FileInfo(path); if (fileInfo.Exists) { Texture2D tex = new Texture2D(0, 0); if (tex.LoadImage(System.IO.File.ReadAllBytes(path))) return tex; } return null; } /// /// 이미지 크기 를 조절 합니다. /// 가로 와 세로 중 큰 쪽을 기준으로 비율을 설정합니다. /// void Resize() { float ratio = 0; if (texture.texture.height < texture.texture.width) ratio = rect.rect.width / texture.texture.width; else ratio = rect.rect.height / texture.texture.height; texture.transform.localScale = new Vector3(ratio, ratio, 0); texture.SetNativeSize(); } }