Frage

I am a starter of Unity developer, I have an image file saved in the device, the file path shown as follow:

string filePath = Application.persistenceDataPath + "myImage.png";

How can I decode it to be byte array so that I can use it? Thank you very much!

War es hilfreich?

Lösung

Solved! Thank you for helps! I have found the answer that absolutely what I need.

byte[] imageData = File.ReadAllBytes(filePath);

Therefore, I can use it any where.

Andere Tipps

If you have the bytes in a byteArray variable, you can do:

    Texture2D tex = new Texture2D(width, height);
    tex.LoadImage(byteArray);
    renderer.material.mainTexture = tex;

But to load from a file, you can use Resources.Load if it's inside a Resources folder, or WWW.LoadFromCacheOrDownload if it's not, but them it will have to be an asset bundle instead of an image, and to build an asset bundle you'll need Unity Pro. Notice that WWW doesn't require the url to be an URL, it can be a path. See examples here:

http://docs.unity3d.com/Documentation/ScriptReference/Resources.Load.html

http://docs.unity3d.com/Documentation/ScriptReference/WWW.LoadFromCacheOrDownload.html

So, to sum up you first load the image into a byte array and then you use the Texture2D class to load the bytes into a texture object.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top