python - 将base64图像字符串解码为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:输入不是有效的 Base-64 字符串,因为它包含非 base 64 字符、两个以上的填充字符或填充字符中的非法字符。
我错过了什么?
解决方案
如果您可以尝试通过通道发送一个非常小的图像(编码、传输、接收)并记录打印另一端接收到的内容,那将会更有帮助。
我的怀疑:
- 不知何故,您没有转换为 base-64
- 您最终发送了太多字节或不必要的字节(空终止字符?)
- 以在末尾添加 CR 或 LF 的方式接收图像内容(例如 'HTTP Response' 正文)
需要更多信息才能提供更好的答案...
推荐阅读
- networking - Packer Tracer:WLAN 配置与多个 VLAN
- syntax-error - Sieve 语言语法错误帮助“如果附近有分号的标识符”
- typescript - 数字的枚举类型突变,但不是字符串?
- android - 无法创建 ViewModel 的实例
- php - 如何命名根据不同条件动态创建的单选按钮组
- flutter - Flutter Framework 如何以及在何处内部调用 StatefulWidget 的 state 的 build 方法?
- scala - 将数据从一个现有行复制到另一个现有行,除了 scala 数据框中的 3 列
- python - 如何使用 scikit-learn 中的 ColumnTransformer 将多个转换应用于同一列
- c++ - 我在 c++03 中的无锁循环队列有什么问题?
- python - 卷积中的通道优先与通道最后