2017-08-07 952 views
0

我在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) 

但他們都不工作,我想。

回答

1

您可以對此使用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