将 base64 图像字符串解码为 Unity 中的图像

Decoding base64 image string to an image in Unity

我正在使用以下代码对 python 结束的图像进行编码,

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5558")

frame = cv2.imread("input.jpg")
encoded, buffer = cv2.imencode('.jpg', frame)
encoded_string = base64.b64encode(buffer)
socket.send_string("output", zmq.SNDMORE)
socket.send_pyobj(encoded_string)

最终,我在Unity端用下面的代码解密了

void Start()
{
    AsyncIO.ForceDotNet.Force();
    NetMQConfig.ManualTerminationTakeOver();
    NetMQConfig.ContextCreate(false);
    string topic = "output";
    subSocket = new SubscriberSocket();
    
    var timeout = new System.TimeSpan(0, 0, 1); //1sec
    string subport;
    
    subSocket.Options.ReceiveHighWatermark = 1000;
    subSocket.Connect("tcp://localhost:5558");
    subSocket.Subscribe(topic);
    bool is_connected =  subSocket.TryReceiveFrameString(timeout, out subport);
    
    Debug.Log(is_connected);

    myTexture = new Texture2D(640, 480, TextureFormat.ARGB32, false);
    
    
}

// Update is called once per frame
void Update()
{
        
    string base64string = subSocket.ReceiveFrameString();
    Debug.Log(base64string.Length);
   
    
    if (base64string.Length > 100)
    {
        byte[] imgBytes = Convert. FromBase64String(base64string);

        
        myTexture.LoadRawTextureData(imgBytes);
        myTexture.Apply();

        rawImg.texture = myTexture;
    }
}

不幸的是,它抛出以下错误,

FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

我错过了什么?

如果您可以尝试通过通道发送一个非常小的图像(编码、传输、接收)并记录打印另一端收到的图像,那将会更有帮助。

我的怀疑:

  • 不知何故你没有转换为 base-64
  • 您最终发送了太多字节或不必要的字节(空终止字符?)
  • 以在最后添加CR或LF的方式接收图片内容(例如'HTTP Response' body)

需要更多信息才能提供更好的答案...