3

I have a jpg file under the tmp folder.

upload_path = /tmp/resized-test.jpg

I have been using the codes below:

Method 1

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

Method 2

def imgToHex(file):
    string = ''
    with open(file, 'rb') as f:
        binValue = f.read(1)
        while len(binValue) != 0:
            hexVal = hex(ord(binValue))
            string += '\\' + hexVal
            binValue = f.read(1)
    string = re.sub('0x', 'x', string) # Replace '0x' with 'x' for your needs
    return string
imgToHex(upload_path)

But none of them are working as I want.

1 Answer 1

9

You can use the binascii package for this. It will convert it in to a hex string.

import binascii
filename = 'test.png'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your solution @pansul-bhatt but when I try to set it into reponse, I get this error: "raise TypeError(repr(o) + \" is not JSON serializable\")" My return code is like this: return { 'header': { 'Content-Type': content_type }, 'body': encoded_string }
Actually, I am trying to apply in AWS Lambda. When I try to give the response like above, I get this error.

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.