Skip to main content
 首页 » 编程设计

python之Python读取jpeg文件,编码成Unicode,放入protobuf

2024年11月01日12开发

我正在将图像从 Python 后端传输到 C++ 后端。我选择了 Google protobuf,结构简单:

message data { 
  optional string image = 1; 
} 

然后我使用 Python 读取图像并将其放入图像字段:

data = server_pb2.data() 
data.image = (open(image_fn).read()) 

但 protobuf 会报错并显示以下消息:

Value Error: [hex data] has type str, but isn't in 7-bit ASCII encoding. Non-ASCII strings must be converted to unicode objects before being added.

我尝试了几种方法来使数据统一编码,但都没有成功。

也许有人以前遇到过这个问题?或者有没有更好的方法来传输图像数据?

谢谢!

请您参考如下方法:

您应该使用 bytes 作为 .proto 文件中的类型,而不是 string。

bytes 用于任意字节序列(例如图像)。 string 用于 UTF-8 或 ASCII 字符序列(例如文本)。