使用Python将图像转换为十六进制格式

3

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

upload_path = /tmp/resized-test.jpg

我一直在使用以下代码:

方法1

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)

但是它们都不能按照我的要求工作。
1个回答

8
您可以使用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 } - Onur Degerli
实际上,我正在尝试在AWS Lambda中应用。当我尝试给出像上面那样的响应时,我会收到这个错误。 - Onur Degerli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接