python怎么获取图片的16进制_python图像PIL到二进制十六进制

1586010002-jmsa.png

from PIL import Image

from PIL import ImageDraw

from PIL import ImageFont

import urllib.request

import io

import binascii

data = urllib.request.urlopen('http://pastebin.ca/raw/2311595').read()

r_data = binascii.unhexlify(data)

stream = io.BytesIO(r_data)

img = Image.open(stream)

draw = ImageDraw.Draw(img)

font = ImageFont.truetype("arial.ttf",14)

draw.text((0, 220),"This is a test11",(0,255,0),font=font)

draw = ImageDraw.Draw(img)

with open(img,'rb') as in_file: #error on here invalid file:

hex_data = in_file.read()

# Unhexlify the data.

bin_data = binascii.unhexlify(bytes(hex_data))

print(bin_data)

Question

converting hex to image and draw a text on the image, after that convert image to binary hex,but having the problem at here with open(img,'rb') as in_file:, how to convert img to hex?

解决方案

The img object needs to be saved again; write it to another BytesIO object:

output = io.BytesIO()

img.save(output, format='JPEG')

then get the written data with the .getvalue() method:

hex_data = output.getvalue()

The PIL-for-python-3 landscape is rather muddled at the moment. The Pillow fork looks to be the best, maintained version out there at the moment. It includes fixes that make saving to a BytesIO object work. If you run into a io.UnsupportedOperation: fileno exception using the above code, you have a version that was not yet fixed, in which case you'll have to resort to using a temporary file instead.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值