使用Python将图像转换为十六进制格式 [英] Convert image into hexadecimal format with Python

查看:588
本文介绍了使用Python将图像转换为十六进制格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a jpg file under the tmp folder.

upload_path = /tmp/resized-test.jpg

我一直在使用以下代码:

I have been using the codes below:

方法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)

但是他们都没有我想要的.

But none of them are working as I want.

推荐答案

您可以为此使用binascii软件包.它将转换为十六进制字符串.

You can use the binascii package for this. It will convert it in to a hex string.

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

这篇关于使用Python将图像转换为十六进制格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆