python图像PIL到二进制十六进制 [英] python Image PIL to binary Hex

查看:2132
本文介绍了python图像PIL到二进制十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)



< h2>问题

将十六进制转换为图像并在图像上绘制文本,然后将图像转换为二进制十六进制,但问题在于与开放(img,'rb')in_file:,如何将img转换为十六进制?

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?

推荐答案

img 对象需要再次保存;把它写到另一个 BytesIO 对象:

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

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

然后获取写入数据与 .getvalue()方法

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

hex_data = output.getvalue()

目前,PIL-for-python-3格局相当混乱。目前,枕头叉看起来是最好的,维护版本。它包含修复程序,可以保存到 BytesIO 对象工作。如果使用上面的代码运行到 io.UnsupportedOperation:fileno 异常,那么您有一个尚未修复的版本,在这种情况下,您必须诉诸使用一个临时文件。

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.

这篇关于python图像PIL到二进制十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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