1. 程式人生 > >Unity 讀取圖片方法

Unity 讀取圖片方法

post 寬高 nbsp c# pix left byte[] 無法 pan

  • 放在資源文件夾下的圖片(本地文件)

    Texture tex = (Texture)Resources.Load("XXX/XXX");

    該方法讀取的圖片只能是在項目路徑下的Resources文件夾下的,如果需要讀取其他地址下的圖片則需要使用如下兩種方式

  • 通過WWW方法讀取

    本地及網絡文件,本地文件需要加file://前綴

    private IEnumerator GetImage(string path)

    {

    WWW www = new WWW("file://" + path);

    yield return www;

    if (www != null && string.IsNullOrEmpty(

    www.error))

    {

    Texture2D texture = new Texture2D(www.texture.width, www.texture.height);

    texture.SetPixels(www.texture.GetPixels());

    texture.Apply(true);

    texture.filterMode = FilterMode.Trilinear;

    }

    }

    WWW方法必須放在協程中執行

  • C# IO方法(本地文件)

    通過C#將文件讀取為Byte[]數據,再使用texture.LoadImage進行裝填,缺陷在創建Texture時無法獲知圖片的寬高

    Texture2D tx = new Texture2D(100, 100);

    tx.LoadImage(getImageByte(filePath);

    private static byte[] getImageByte(string imagePath)

    {

    FileStream files = new FileStream(imagePath, FileMode.Open);

    byte[]

    imgByte = new byte[files.Length];

    files.Read(imgByte, 0, imgByte.Length);

    files.Close();

    return imgByte;

    }

Unity 讀取圖片方法