直接加載非Readable的Texture,是不能訪問其像素數據的:
// 加載 var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath); var data = tex.GetPixels();
上面的代碼匯報如下錯誤:
the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.
也就是說需要將Texture標記為可讀狀態,但是有時候在寫一些圖片批處理解析的時候,大量修改readable,用完以后再改回來,是非常耗時的,所以需要使用別的方式來讀取Texture的像素數據。
// 加載 var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath); FileStream fs = File.OpenRead(fileFullname); fs.Seek(0, SeekOrigin.Begin); byte[] image = new byte[(int)fs.Length]; fs.Read(image, 0, (int)fs.Length); var texCopy = new Texture2D(tex.width, tex.height); texCopy.LoadImage(image);
這樣可以不修改readable,並且可以讀取圖像的信息。
PS:這樣讀出來的數據,texture的尺寸是圖片的本地尺寸,和unity import setting后的大小可能會不一樣。