【问题标题】:Unity Serialize and Encoding spriteUnity 序列化和编码精灵
【发布时间】:2019-03-06 17:16:00
【问题描述】:

我正在尝试在 Android 设备上下载并保存文件。它在 PC 上运行良好,但我的 android 手机上有一个视觉错误。请看屏幕

我的代码: 这就是我下载和序列化它的方式

Icon = Sprite.Create(texture2dd, new Rect(0.0f, 0.0f, texture2dd.width, texture2dd.height), new Vector2(0.5f, 0.5f), 100.0f);

byte[] texturebytes = Icon.texture.GetRawTextureData();
File.WriteAllText(Application.persistentDataPath + "/icon", Encoding.Default.GetString(texturebytes));
File.WriteAllText(Application.persistentDataPath + "/iconinfo", Icon.texture.width + "@@@" + Icon.texture.height);

这就是我稍后尝试加载它的方式:

string[] info = File.ReadAllText(path + "info").Split(new string[] { "@@@" }, StringSplitOptions.None);
int width, height;
int.TryParse(info[0], out width);
int.TryParse(info[1], out height);
byte[] bytesIcon = Encoding.Default.GetBytes(File.ReadAllText(path));
Texture2D iconText = new Texture2D(width, height, TextureFormat.ARGB32, false);
iconText.LoadRawTextureData(bytesIcon);
iconText.Apply();
return Sprite.Create(iconText, new Rect(0, 0, width, height), new Vector2(0.5f, 0.5f));

我认为编码类型有问题,但我尝试了所有编码类型,它仍然不起作用,并加载了一些错误纹理。

【问题讨论】:

    标签: unity3d serialization encoding sprite


    【解决方案1】:

    您应该将其实际保存为.png.jpg 格式,而不是使用GetRawTextureData()LoadRawTextureData!与纯 .jpg.png 文件数据相比,“RawTextureData”非常庞大。


    改为使用EncodeToPNG(或EncodeToJPG,如果质量不是那么重要 - 记住也要采用文件结尾)和LoadImage

    另外LoadImage 实际上“知道”图像大小(因为它被编码到pngjpg 文件中)所以根本不需要你的iconinfo 文件!

    类似

    // ...
    Icon = Sprite.Create(texture2dd, new Rect(0.0f, 0.0f, texture2dd.width, texture2dd.height), Vector2.one * 0.5f, 100.0f);
    
    byte[] texturebytes = Icon.texture.EncodeToPNG();
    File.WriteAllText(Application.persistentDataPath + "/icon.png", Encoding.Default.GetString(texturebytes));
    // ...
    

    (也许还可以查看this answer 以了解其他写入文件的方式。)

    // ...
    byte[] bytesIcon = Encoding.Default.GetBytes(File.ReadAllText(path));
    // as the example in the documentation states:
    //   Texture size does not matter, since
    //   LoadImage will replace it with incoming image size.
    Texture2D iconText = new Texture2D(2, 2);
    iconText.LoadImage(bytesIcon);
    // Also from the documentation:
    //   Texture will be uploaded to the GPU automatically; there's no need to call Apply.
    return Sprite.Create(iconText, new Rect(0, 0, iconText.width, iconText.height), Vector2.one * 0.5f);
    

    是的,另一个问题可能仍然是您使用了Encoding.Default(请参阅here)所以也许您还应该使用固定编码,例如Encoding.UTF8


    虽然为了加载文件,我实际上更喜欢使用UnityWebRequest,它也可以用于本地文件存储中的文件!

    【讨论】:

    • 感谢您的回复。我试过了,但它不加载图像。只是白色方块(
    • 您是否尝试使用FileStream 解决方案来代替加载?我不确定ReadAllText 是否会导致一些问题
    猜你喜欢
    • 2019-07-13
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    • 2016-03-30
    相关资源
    最近更新 更多