4

What I want is to read png file as byte[] array. I need that array in order to send it to the remote server via HTTP POST request. My code looks like this:

Sprite sprite = Resources.Load<Sprite>("Images/" + _filename);
print("Sprite loaded.");
print("Texture size: " + sprite.texture.width + ", " + sprite.texture.height);
byte[] bytes = sprite.texture.EncodeToPNG();
print("Done.");

Logs look like this (I ran the app in unity editor):

Sprite loaded. 
Texture size: 750, 1334

It never prints "Done". I've waited several minutes. There are no errors in unity console. File is about 1MB so it's not a huge photo. It looks like sprite is loaded without a problem, but it can't be converted to byte[] array (as png). What's going on?

Makalele
  • 7,431
  • 5
  • 54
  • 81
  • 1
    Add try-catch to the code. Maybe it will help to detect some error ```try { byte[] bytes = sprite.texture.EncodeToPNG(); } catch (ex) { print(ex); } print("Done.");``` – KingGary Mar 02 '20 at 07:59
  • Btw do you need to go through `Sprite`? You could directly load the image as `Texture2D` right? – derHugo Mar 02 '20 at 08:08
  • 1
    Also don't use `Resources` at all! Rather directly drag your texture into `public Texture2D texture;` via the Inspector – derHugo Mar 02 '20 at 08:27

1 Answers1

1

@KingGary thanks for the hint!

I've never thought that it'll raise an exception while using try-catch when there's none without it.

The exception is:

System.ArgumentException: Texture 'test_image' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.

The solution is to select the file in the unity editor and enable "Read/Write Enabled" in the properties window.

Makalele
  • 7,431
  • 5
  • 54
  • 81