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#.
To convert a byte array to an image. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).
Any image is merely a sequence of bytes structured in accordance with whatever underlying format used to represent it, eg color data, layers, dimensions, etc. The significance of any byte(s) you see during debugging is entirely dependent upon the native format of the image, eg PNG, TIFF, JPEG, BMP, etc.
Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With