Python PIL Image for Binary Hex

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 drawing text on the image, then converting the image to binary hex, but having a problem here with open(img,'rb') as in_file: how to convert img to hex?

+4
source share
1 answer

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

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

then get the recorded data using the .getvalue() method:

 hex_data = output.getvalue() 

At the moment, the PIL-for-python-3 landscape is rather confusing. The fork cushion looks like the best supported version out there right now. It includes corrections that make the BytesIO object BytesIO in operation. If you are using the io.UnsupportedOperation: fileno exception using the code above, you have a version that has not yet been fixed, in which case you will have to resort to using a temporary file.

+11
source

All Articles