【问题标题】:Convert image into hexadecimal format with Python使用 Python 将图像转换为十六进制格式
【发布时间】:2023-04-02 02:27:01
【问题描述】:

tmp 文件夹下有一个 jpg 文件。

upload_path = /tmp/resized-test.jpg

我一直在使用下面的代码:

方法一

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

方法二

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)

但它们都没有按我的意愿工作。

【问题讨论】:

    标签: python image hex


    【解决方案1】:

    您可以为此使用 binascii 包。它会将其转换为十六进制字符串。

    import binascii
    filename = 'test.png'
    with open(filename, 'rb') as f:
        content = f.read()
    print(binascii.hexlify(content))
    

    【讨论】:

    • 感谢您的解决方案@pansul-bhatt 但是当我尝试将其设置为响应时,我收到此错误:"raise TypeError(repr(o) + \" is not JSON serializable\")" 我的返回码是这样的:return { 'header': { 'Content-Type': content_type }, 'body': encoded_string }
    • 其实我是在尝试申请AWS Lambda。当我尝试给出上述响应时,我收到此错误。
    猜你喜欢
    • 2013-09-14
    • 2010-10-15
    • 2010-12-15
    • 2011-08-13
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多