7

I have a byte[] array which reads a local file and then I assign it to a unity Texture2D. The image is assigned using the im.sprite = Sprite.Create() function.

The problem I have is that I need to detect the width and height of the image from the byte array so I can adjust adjust the texture size and avoid image stretching on the unity scene at run-time.

Do you know how I could use a library or function of some kind to maybe create a temp image from the image byte array and then see the desired width and height before I create the sprite and apply the texture?

I've found solutions in Java but can't seen to get it working by adapting in c#.

2
  • Possible duplicate of Byte Array to Image Conversion Commented May 2, 2017 at 12:51
  • @Mat It is not a duplicate. This is Unity. Commented May 2, 2017 at 13:07

1 Answer 1

9

When Texture2D.LoadImage is called, it will automatically replace the Texture2D instance with the size of the image. You can then grab the width and height from the Texture2D instance and pass it to the Sprite.Create function.

Load your image to byte array

byte[] imageBytes = loadImage(savePath);

Create new Texture2D

Texture2D texture = new Texture2D(2, 2);

Load it into a Texture2D. After LoadImage is called, 2x2 will be replaced with the size of that image.

texture.LoadImage(imageBytes);

Your image component

Image im = GetComponent<Image>();

You can create a new Rect with it and then pass it to your Sprite function to create new Sprite.

im.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

Read more about the Texture2D.LoadImage function here.

You just need Texture2D.width and Texture2D.height variables.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.