Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将图像数组转换为JSON文件,并在C之后解码#_C#_Json_Unity3d - Fatal编程技术网

C# 将图像数组转换为JSON文件,并在C之后解码#

C# 将图像数组转换为JSON文件,并在C之后解码#,c#,json,unity3d,C#,Json,Unity3d,我想创建一个包含图像的数组,然后将其转换为JSON文件。然后将此文件上载到服务器。然后将这个文件下载到一个项目中,然后我想将JSON文件转换回以前的图像数组,这样我就可以从其中检索图像。那么这个编解码过程是如何实现的呢?这在C#中可能吗?(更确切地说,我使用的是Unity3D) 谢谢一般来说,以基于文本的格式存储二进制数据是个坏主意。。。可以这样做,但需要Base64编码字符串(和)。。这需要比原始字节本身更多的内存 但是,是的,你可能会使用类似于 // The root JSON object

我想创建一个包含图像的数组,然后将其转换为JSON文件。然后将此文件上载到服务器。然后将这个文件下载到一个项目中,然后我想将JSON文件转换回以前的图像数组,这样我就可以从其中检索图像。那么这个编解码过程是如何实现的呢?这在C#中可能吗?(更确切地说,我使用的是Unity3D)
谢谢

一般来说,以基于文本的格式存储二进制数据是个坏主意。。。可以这样做,但需要Base64编码字符串(和)。。这需要比原始字节本身更多的内存

但是,是的,你可能会使用类似于

// The root JSON object
[Serializable]
public class Root
{
    public List<ImageData> encodedImages = new List<ImageData>();

    // Empty constructor required by serializer
    public Root(){ }

    public Root(Texture2D[] textures)
    {
        foreach(var tex in textures)
        {
            encodedImages.Add(new ImageData(tex));
        }
    }
}

// Data for each encoded image/Texture2D
[Serializable]
public class ImageData
{
    public int width;
    public int height;
    public int type;
    public string encodedData;

    // empty constructor required by serializer
    public ImageData() { }

    pubilc ImageData(Texture2D tex)
    {
        width = tex.width;
        height = tex.height;
        type = (int)tex.format;

        // Note that this is SLOW!
        var bytes = tex.EncodeToPNG();

        encodedData = Convert.ToBase64String(bytes);
    }

    public Texture2D GetTexture()
    {
        var bytes = Convert.FromBase64String(encodedData);

        var tex = new Texture(width, height, (TextureFormat)type, false);
        tex.LoadRawTextureData(bytes);
        tex.Apply();

        return tex;
    }
}

public string Encode(Texture2D[] textures)
{
    var output = new Root(textures);

    return JsonUtility.ToJson(output);
}

public Texture2D[] Decode(string json)
{
    var root = JsonUtility.FromJson<Root>(json);

    var count = root.encodedImages.Length;
    var output = new Texture2D[count];

    for(var i = 0; i < count; i++)
    {
        output[i] = root.encodedImages[i].GetTexture();
    }

    return output.ToArray();
}


注意:在智能手机上输入,但我希望想法变得清晰

您可以将所有图像转换为base64字符串,创建这些字符串的数组并将其转换为JSON。检索JSON时,可以将base64字符串转换回图像。您确定需要使用JSON吗?你看过资产包了吗?