Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image width and height from a byte array data

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#.

like image 495
Diego Avatar asked May 02 '17 12:05

Diego


People also ask

How can I get image from byte array?

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).

How is an image stored in a byte array?

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.

How can I get bytes of an image?

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.


1 Answers

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.

like image 148
Programmer Avatar answered Oct 22 '22 21:10

Programmer