项目中有些图片需要后期进行维护,一般都会将其存放至指定目录下,但这样一来很容易暴露,我们一般会将其简单处理加密,例如转换成二进制文件等。这时需要在Unity里读取它文件**.byte,将其转换为图片,以达到使用效果。点击可下载此资源
/**
*Copyright(C) 2017 by MMHD
*All rights reserved.
*FileName: LoadImg.cs
*Author: Joel
*Version: 1.0
*Date: 2017/12/6
*Description:Byte[]转Image
*History: By307035570
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
public class LoadImg : MonoBehaviour {
private string url;
void Start () {
url = Application.dataPath + "/StreamingAssets/";
//url = "D:\\Photo\\";//本地图片
StartCoroutine(GetBytesToPic());
}
/// <summary>
/// 将字节转换为图片,并赋给图片组件显示
/// </summary>
/// <returns></returns>
IEnumerator GetBytesToPic()
{
int width = 1920;
int height =1080;
byte[] bytes = file2stream(url + "0.byte");
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
yield return new WaitForSeconds(0.01f);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
transform.GetComponent<Image>().sprite = sprite;
yield return new WaitForSeconds(0.01f);
Resources.UnloadUnusedAssets();
}
/// <summary>
/// 读取字节流
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public byte[] file2stream(string fileName)
{
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
return bytes;
//Stream stream = new MemoryStream(bytes);
//return stream;
}
}