Reputation: 371
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#.
Upvotes: 7
Views: 6961
Reputation: 125245
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.
Upvotes: 9