- Home /
Exception Loading PNG Bytes for Texture
I am storing a PNG in a textfile. I convert it to a PNG using:
myTexture.EncodeToPNG()
and then save. I then load the bytes with:
Texture2D texture = new Texture2D(100, 100);
texture.LoadRawTextureData(myPNGBytes);
This throws the following error:
UnityException: LoadRawTextureData: not enough data provided (will result in overread).
I know that the PNG is stored correctly because when I use an online base64 converter the image is displayed. I've tried loading with several different formats, but all throw the same exception. What am I doing wrong?
EDIT: when I check the format of the Texture2D before saving, it says RGB24. I get the same error when I instantiate the texture with this format and then load.
EDIT: Even when I skip the saving step and just do:
byte[] bytes = result.Texture.EncodeToPNG();
Texture2D texture = new Texture2D(100, 100);
texture.LoadRawTextureData(bytes);
I get the same exception. So my question is what is the inverse of Texture2D.EncodeToPNG()
Answer by andrew-lukasik · Nov 17, 2020 at 07:49 PM
EncodeToPNG
bytes aren't raw. Those're, well, encoded.
byte[] bytes = texture.GetRawTextureData();// raw bytes to save
texture.LoadRawTextureData( bytes );// this how to load raw bytes
texture.Apply( updateMipmaps:true , makeNoLongerReadable:true );// uploads changes to GPU
Raw in this context mean GPU-ready. Encoded to png, on the other hand, are file system - ready.
Alternatively, store/read PNG bytes:
byte[] PNGbytes = texture.EncodeToPNG();// png-encoded bytes to save
texture.LoadImage( PNGbytes );// this is how to load png-encoded bytes
texture.Apply( updateMipmaps:true , makeNoLongerReadable:true );// uploads changes to GPU
PS: You may want to compress these raw bytes before saving (+decompress after loading) to save on storage space.
Your answer
![](https://koobas.hobune.stream/wayback/20220613015956im_/https://answers.unity.com/themes/thub/images/avi.jpg)