Byte[]转Image

项目中有些图片需要后期进行维护,一般都会将其存放至指定目录下,但这样一来很容易暴露,我们一般会将其简单处理加密,例如转换成二进制文件等。这时需要在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;
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值