验证了一下RGBA32格式在Unity的读取方式

验证了一下Texture2D.LoadRawTextureData(Byte[] bytes)的读取方式是怎么样的,就是很简单的从头读到尾
文件格式很简单,比如一个3x2的图片那就是:
RGBA,RGBA,RGBA
RGBA,RGBA,RGBA
(文件里逗号和换行是没有的,只是为了展示图片存储格式)
每一个字母代表一个byte,比如字母A =255就是不透明 A=0就是透明

using UnityEngine;
using System.IO;

public class RGBATest : MonoBehaviour
{
    public Texture2D tex;
    public TextureFormat format = TextureFormat.RGBA32;
    public Vector2Int resolution = new Vector2Int(1080, 1920);
    public string datapath = "H:/UE4/Saved/PersistentDownloadDir/img.raw";
    // Start is called before the first frame update
    void Start()
    {
        //读取RGBA32格式存储的图片文件
        FileStream fs = new FileStream(datapath, FileMode.Open);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, (int)fs.Length);
        Debug.Log(fs.Length);

        //创建图片,前提是,必须知道raw格式的分辨率是什么.我这里是1080x1920
        tex = new Texture2D(resolution.x, resolution.y, format,false);

        //方式1,API直接读
        //tex.LoadRawTextureData(bytes);

        //方式2,自己读然后赋值,发现和方式1是一模一样的
        Color32[] colors = new Color32[resolution.x * resolution.y];
        for (int i = 0; i < colors.Length; i++)
        {
            colors[i].r = bytes[i * 4 + 0];
            colors[i].g = bytes[i * 4 + 1];
            colors[i].b = bytes[i * 4 + 2];
            colors[i].a = bytes[i * 4 + 3];
        }
        tex.SetPixels32(colors);

        //提交给gpu刷新图片
        tex.Apply();

        //我这里是Unity默认的Plane面片,设置了一下显示在面片上
        MeshRenderer mesh = this.gameObject.GetComponent();
        Material matt = new Material(mesh.material);
        mesh.material = matt;
        mesh.material.SetTexture("_MainTex", tex);
        if (resolution.x > resolution.y)
        {
            mat.transform.localScale = new Vector3(resolution.x / (float)resolution.x, 1, resolution.y / (float)resolution.x);
        }
        else
        {
            mat.transform.localScale = new Vector3(resolution.x / (float)resolution.y, 1, resolution.y / (float)resolution.y);
        }
    }
}

你可能感兴趣的:(验证了一下RGBA32格式在Unity的读取方式)