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

问题描述:

我在tmp文件夹下有一个jpg文件。用Python将图像转换成十六进制格式

upload_path = /tmp/resized-test.jpg 

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

方法1种

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

方法2

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) 

但他们都不工作,我想。

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

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

感谢您的解决方案@ pansul - 布哈特但是当我尝试将它设置成效应初探,我得到这个错误:““养类型错误(再版(O)+ \”是不是JSON序列化\“)”'我返回的代码是这样的:回报{ ' '头':{ '的Content-Type':CONTENT_TYPE }, '体':encoded_string }' – onurdegerli

+0

你让你的打印过程中这个错误? –

+0

其实,我试图在AWS Lambda中应用。当我尝试提供上述回复时,我收到此错误。 – onurdegerli