using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class ImageLoader : MonoBehaviour
{
? ? [SerializeField]
? ? private string _relativePath;
? ? private Texture2D _texture;
? ? private Image _img;
? ? public string RelativePath
? ? {
? ? ? ? get { return _relativePath; }
? ? ? ? set {
? ? ? ? ? ? _relativePath = value;
? ? ? ? ? ? ReLoadImage();
? ? ? ? }
? ? }
? ? private void Awake()
? ? {
? ? ? ? _img = GetComponent<Image>();
? ? }
? ? void Start()
? ? {
? ? ? ? ReLoadImage();
? ? }
? ? public void ReLoadImage()
? ? {
? ? ? ? if (!string.IsNullOrEmpty(_relativePath))
? ? ? ? {
? ? ? ? ? ? var data = ReadPNG(_relativePath);
? ? ? ? ? ? if (data != null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? _texture = new Texture2D(1, 1);
? ? ? ? ? ? ? ? _texture.LoadImage(data);
? ? ? ? ? ? ? ? _img.sprite = Sprite.Create(_texture, new Rect(0, 0, _texture.width, _texture.height), new Vector2(0, 0));
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? _img.sprite = null;
? ? }
? ? private byte[] ReadPNG(string path)
? ? {
? ? ? ? string fullPath = path;
? ? ? ? if (!string.IsNullOrEmpty(fullPath))
? ? ? ? {
? ? ? ? ? ? FileStream fileStream = new FileStream(fullPath, FileMode.Open, System.IO.FileAccess.Read);
? ? ? ? ? ? fileStream.Seek(0, SeekOrigin.Begin);
? ? ? ? ? ? byte[] binary = new byte[fileStream.Length];?
? ? ? ? ? ? fileStream.Read(binary, 0, (int)fileStream.Length);
? ? ? ? ? ? fileStream.Close();
? ? ? ? ? ? fileStream.Dispose();
? ? ? ? ? ? fileStream = null;
? ? ? ? ? ? return binary;
? ? ? ? }
? ? ? ? return null;
? ? }
}