我在tmp
文件夹下有一个jpg文件。
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)
但他们都没有按我的意愿工作。
答案 0 :(得分:1)
您可以使用binascii包。它会将其转换为十六进制字符串。
import binascii
filename = 'test.png'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))