如何在ctypes中将无符号字节数组转换为base64字符串

2024-09-28 22:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C SDK返回的图像缓冲区

我可以写入本地图像并将其作为base64字符串读取,但这需要额外的步骤。你知道吗

如何将字节数组直接转换为base64字符串,以便在网络请求中发送它?你知道吗

image = (ctypes.c_ubyte*s.dwDataLen)()
ctypes.memmove(image, s.pBuffer, s.dwDataLen)

我尝试使用base64.encodestring,但出现了这个错误

TypeError: expected single byte elements, not '<B' from c_ubyte_Array_8716

Tags: 字符串图像image网络字节sdk步骤数组
2条回答

试试这个:

import ctypes
import base64

image = (ctypes.c_ubyte * s.dwDataLen)()
ctypes.memmove(image, s.pBuffer, s.dwDataLen)
# Convert the image to an array of bytes
buffer = bytearray(image)
encoded = base64.encodebytes(buffer)

如果您正在使用base64.b64encode,您应该能够将image传递给它:

import ctypes
import base64

image = (ctypes.c_ubyte * s.dwDataLen)()
ctypes.memmove(image, s.pBuffer, s.dwDataLen)
encoded = base64.b64encode(image)

您可以使用base64模块

import base64

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

这种情况与Encoding an image file with base64类似

相关问题 更多 >