1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using System;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Net;
- using System.Threading.Tasks;
- using UnityEngine;
- namespace ET
- {
- public class UrlImageLoader: Singleton<UrlImageLoader>
- {
- const string ImgPrefix = "omm_di_";
- private int FileIndex = 0;
- private string TmpImgFile(String url)
- {
- string ext = ".png";
- if (url.EndsWith(".jpg") || url.EndsWith(".png") || url.EndsWith(".gif"))
- {
- ext = url.Substring(url.Length - 4);
- }
- var file = ImgPrefix + (++FileIndex) + ext;
- return Path.Combine(Application.persistentDataPath, file);
- }
- public async Task<Texture2D> LoadImage(string url)
- {
- try
- {
- var imgFile = TmpImgFile(url);
- await new WebClient().DownloadFileTaskAsync(url, imgFile);
- var stream = new FileStream(imgFile, FileMode.Open, FileAccess.Read);
- Image img = Image.FromStream(stream);
- Texture2D tex = new Texture2D(img.Width, img.Height);
- img.Dispose();
- stream.Seek(0, SeekOrigin.Begin);
- var bytes = new Byte[stream.Length];
- stream.Read(bytes, 0, bytes.Length);
- ImageConversion.LoadImage(tex, bytes, false);
- stream.Close();
- return tex;
- }
- catch(Exception e)
- {
- Log.Error($"Load error: url\n" + e);
- }
- return null;
- }
- }
- }
|