Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert image into hexadecimal format with Python

Tags:

python

image

hex

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.

like image 761
Onur Degerli Avatar asked Jul 14 '26 10:07

Onur Degerli


1 Answers

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))
like image 88
Pansul Bhatt Avatar answered Jul 16 '26 00:07

Pansul Bhatt