URL 이미지 다운 및 관리 코드
URL을 기준으로 Texture를 읽고 저장하는 코드이다.
UnityWebRequestTexture를 사용해서 URL의 이미지를 Texture로 변환시킨다.
반응형
<TextureLoaderformURL>
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using UnityEngine.Networking;
using System.IO;
/// <summary>
/// URL에서 이미지를 읽고 저장 처리하는 코드
/// </summary>
public class TextureLoaderformURL
{
private static Dictionary<string, Texture2D> _textureCahce = new Dictionary<string, Texture2D>();
private static Dictionary<string, Texture2D> Textures
{
get {
return _textureCahce;
}
set
{
_textureCahce = value;
}
}
public static Task<Texture2D> GetTexture(string _url, bool _nonReadable = false, bool _fileSave =false)
{
var tcs = new TaskCompletionSource<Texture2D>();
if (Textures.ContainsKey(_url) ==false)
{
if (string.IsNullOrEmpty(_url))
{
throw new System.Exception($"[GetTexture2DfromURL] URL is Null ");
}
Texture2D returnTexture2D = null;
UnityWebRequest www = UnityWebRequestTexture.GetTexture(_url, _nonReadable);
var asyncOperation = www.SendWebRequest();
asyncOperation.completed += (operation) =>
{
if (operation.isDone == false)
throw new System.Exception($"[GetTexture2DfromURL] Exception :{_url}");
if (www.result == UnityWebRequest.Result.ConnectionError)
throw new System.Exception($"[GetTexture2DfromURL] Network Error :{_url}");
returnTexture2D = ((DownloadHandlerTexture)www.downloadHandler).texture;
if (returnTexture2D != null)
Textures.Add(_url, returnTexture2D);
tcs.SetResult(Textures[_url]);
FileSave($"{System.DateTime.Now.ToString("yyyyMMddHHmm")}.png", returnTexture2D);
};
}
return tcs.Task;
}
private static void FileSave(string _name, Texture2D _texture )
{
string fileRootPath = string.Empty;
string filePath = string.Empty;
#if UNITY_EDITOR
fileRootPath = Application.streamingAssetsPath;
#elif UNITY_IOS
fileRootPath = Application.persistentDataPath;
#elif UNITY_ANDROID
fileRootPath = Application.persistentDataPath;
#endif
//Root Folder Create
if (!Directory.Exists(fileRootPath))
{
Directory.CreateDirectory(fileRootPath);
}
filePath = Path.Combine(fileRootPath, _name);
if (File.Exists(filePath))
{
Debug.LogError($"[SmartTexture] File Exist Error : {_name}");
return;
}
File.WriteAllBytes(filePath, _texture.EncodeToPNG());
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}
}
<사용방법>
SetTexture( await TextureLoaderformURL.GetTexture(
"https://firebasestorage.googleapis.com/v0/b/fir-test-58196.appspot.com/o/temp.png?alt=media&token=fbaadf6e-f462-4730-8ff3-311146007341", false,true));
UnityWebRequestTexture .GetTexture : [링크]
★☆☆☆☆
반응형
댓글