python 图像 (.jpeg) 转换为十六进制代码

2 投票
3 回答
5796 浏览
提问于 2025-04-18 14:16

我在使用一台热敏打印机,这台打印机可以打印图片,但它需要把数据转换成十六进制格式。为此,我需要一个Python函数来读取一张图片,并返回包含该图片数据的十六进制值。

我现在用这种格式把十六进制数据发送给打印机:

content = b"\x1B\x4E"

请问在Python2.7中,最简单的方法是什么?祝一切顺利;

3 个回答

0

首先,读取一个jpg图片,然后把它转换成一串十六进制的值。接着,反过来操作:把这串十六进制的值再写回去,生成一个jpg文件...

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)
0

这样怎么样:

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)

或者对于一个函数,可以这样写:

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

注意:如果你使用 struct.pack 来写入数据,那么不一定需要做 re.sub 的部分,但这样做可以让数据变成你需要的格式。

0

我不太明白你说的“十六进制格式”是什么意思,不过如果你需要把整个文件作为字节序列获取,可以这样做:

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

如果你的打印机需要以其他格式(比如每个像素用8位值表示)来处理图像,那么可以试试pillow这个库,它有很多处理图像的功能,并且支持多种输入和输出格式。

撰写回答