'python image (.jpeg) to hex code

I operate with a thermal printer, this printer is able to print images, but it needs to get the data in hex format. For this I would need to have a python function to read an image and return a value containing the image data in hex format. I currently use this format to sent hex format to the printer:

content = b"\x1B\x4E"

Which is the simplest way to do so using Python2.7? All the best;



Solution 1:[1]

I don't really know what you mean by "hex format", but if it needs to get the whole file as a sequence of bytes you can do:

with open("image.jpeg", "rb") as fp:
    img = fp.read()

If your printer expects the image in some other format (like 8bit values for every pixel) then try using the pillow library, it has many image manipulation functions and handles a wide range of input and ouput formats.

Solution 2:[2]

How about this:

with open('something.jpeg', 'rb') as f:
    binValue = f.read(1)
    while len(binValue) != 0:
        hexVal = hex(ord(binValue))
        # Do something with the hex value
        binValue = f.read(1)

Or for a function, something like this:

import re
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

Note: You do not necessarily need to do the re.sub portion if you use struct.pack to write the bits, but this will get it into the format that you need

Solution 3:[3]

Read in a jpg and make a string of hex values. Then reverse the procedure. Take a string of hex and write it out as a jpg file...

import binascii

with open('my_img.jpg', 'rb') as f:
    data = f.read()

print(data[:10])

im_hex = binascii.hexlify(data)

# check out the hex...
print(im_hex[:10])

# reversing the procedure
im_hex = binascii.a2b_hex(im_hex)
print(im_hex[:10])

# write it back out to a jpg file
with open('my_hex.jpg', 'wb') as image_file:
    image_file.write(im_hex)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anonymous_user_13
Solution 2
Solution 3 Harley