我想要的是将 png 文件读取为 byte[] 数组。我需要该数组才能通过 HTTP POST 请求将其发送到远程服务器。我的代码如下所示:
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.");
日志如下所示(我在统一编辑器中运行该应用程序):
Sprite loaded.
Texture size: 750, 1334
它从不打印“完成”。我已经等了几分钟了。 Unity控制台没有错误。 文件大约 1MB,所以不是一张很大的照片。看起来 Sprite 加载没有问题,但无法转换为 byte[] 数组(如 png)。 这是怎么回事?
最佳答案
@KingGary 感谢您的提示!
我从来没有想过,当没有 try-catch 时,它会引发异常。
异常(exception)情况是:
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.
解决方案是在Unity编辑器中选择该文件,并在属性窗口中启用“Read/Write Enabled”。
关于c# - EncodeToPNG 挂起脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60484595/