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
6
  • Possible duplicate of Python 3 and base64 encoding of a binary file Commented Jun 13, 2019 at 5:23
  • 1
    Have a look at base64.encodebytes Commented Jun 13, 2019 at 5:25
  • Which part of the answer worked for your problem? Commented Jun 14, 2019 at 4:32
  • What is the type of s.pBuffer? There may be a way to eliminate the extra copy to another buffer type. Commented Jun 15, 2019 at 3:06
  • @DavidCullen Second part of your answer, the one with base64.b64encode Commented Jun 16, 2019 at 11:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

This would requires an extra write and read operation. Is there a method where a direct conversion from bytes to b64 string?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.