EncodeToPNG hangs the script

Viewed 310

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?

1 Answers

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

Related