1

I have an image buffer returned from a C SDK,

I can write to a local image and read it as base64 string but this requires an extra step.

How can I turn the byte array into a base64 string directly so that I can send it in a network request?

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

I tried using base64.encodestring but got this error

TypeError: expected single byte elements, not '<B' from c_ubyte_Array_8716
Moore Tech
  • 199
  • 1
  • 17
  • Possible duplicate of [Python 3 and base64 encoding of a binary file](https://stackoverflow.com/questions/37944806/python-3-and-base64-encoding-of-a-binary-file) –  Jun 13 '19 at 05:23
  • 1
    Have a look at [base64.encodebytes](https://docs.python.org/3.5/library/base64.html#base64.encodebytes) –  Jun 13 '19 at 05:25
  • Which part of the answer worked for your problem? –  Jun 14 '19 at 04:32
  • What is the type of `s.pBuffer`? There may be a way to eliminate the extra copy to another buffer type. – Mark Tolonen Jun 15 '19 at 03:06
  • @DavidCullen Second part of your answer, the one with `base64.b64encode` – Moore Tech Jun 16 '19 at 11:29
  • @MarkTolonenIt is a `byte` pointer. I declare it as `c_void_p` in my struct definition – Moore Tech Jun 21 '19 at 08:37

2 Answers2

1

you can use base64 module

import base64

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

the case is similar with Encoding an image file with base64

yovie
  • 81
  • 2
  • This would requires an extra write and read operation. Is there a method where a direct conversion from bytes to b64 string? – Moore Tech Jun 13 '19 at 05:09
0

Try this:

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)

If you are using base64.b64encode, you should be able to pass image to it:

import ctypes
import base64

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