【问题标题】:python image (.jpeg) to hex codepython图像(.jpeg)到十六进制代码
【发布时间】:2014-09-13 09:20:32
【问题描述】:

我使用的是热敏打印机,这台打印机可以打印图像,但需要获取十六进制格式的数据。为此,我需要一个 python 函数来读取图像并返回一个包含十六进制格式图像数据的值。 我目前使用这种格式将十六进制格式发送到打印机:

content = b"\x1B\x4E"

使用 Python2.7 最简单的方法是什么? 万事如意;

【问题讨论】:

  • Python Imaging Library (PIL) 是主要的图像处理库,尽管它已被废弃多年(3.x fork 是 Pillow)。它仍然最适合基本的图像操作。您还可以使用 OpenCV 读取图像。您仍然需要弄清楚如何将原始像素数据更改为打印机所需的格式。

标签: python printing hex


【解决方案1】:

我真的不知道您所说的“十六进制格式”是什么意思,但是如果它需要将整个文件作为字节序列获取,您可以这样做:

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

如果您的打印机需要其他格式的图像(例如每个像素的 8 位值),那么请尝试使用 pillow 库,它具有许多图像处理功能并可以处理各种输入和输出格式。

【讨论】:

    【解决方案2】:

    这个怎么样:

    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 部分,但这会将其转换为您需要的格式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 2015-03-21
      • 2020-11-20
      • 2018-05-17
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多