How to convert System.IO.Stream into a Texture in

2019-03-06 01:31发布

问题:

I'm building a client-side Android app in Unity, and when it downloads a jpg from an AWS S3 server, the result comes back as a System.IO.Stream.

However my limited knowledge of Mono and .Net means that I'm struggling to figure out how to turn this System.IO.Stream blob of data into a Texture in Unity, that I can then set on a quad in my scene.

I've seen promising examples of code online like: var img = Bitmap.FromStream(stream); yet System.Drawing.Bitmap is not supported in Unity for Android as far as I can tell - does anyone have any suggestions?

Thanks in advance!

(The exact example code I'm using to download from AWS S3 is the GetObject() function that can be found here http://docs.aws.amazon.com/mobile/sdkforunity/developerguide/s3.html, but in their example they use a System.IO.StreamReader which only works with reading in text not byte data for images)

回答1:

You are looking for the LoadImage function from the Texture2D class. This function converts PNG/JPG image byte array into a texture.

Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(stream);

The stream variable must be byte array(byte[]) from the internet / AWS S3 serve.