Python PIL字节到图像

时间:2013-02-07 19:44:00

标签: python image binary python-imaging-library drawtext

import PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import urllib.request

with urllib.request.urlopen('http://pastebin.ca/raw/2311595') as in_file:
    hex_data = in_file.read()
print(hex_data)
img = Image.frombuffer('RGB', (320,240), hex_data) #i have tried fromstring
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf",14)
draw.text((0, 220),"This is a test11",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.jpg")

我试图将二进制转换为图像,然后绘制文本。但我得到错误:

img = Image.frombuffer('RGB', (320,240), hex_data) 
raise ValueError("not enough image data")
ValueError: not enough image data

我已在此处http://pastebin.ca/raw/2311595上传了字节字符串 和图片大小我可以肯定是320x240

其他

这里是我可以肯定的图片字节字符串是来自320x240,只需运行代码就会从字节字符串中创建一个图像

import urllib.request
import binascii
import struct

# Download the data.
with urllib.request.urlopen('http://pastebin.ca/raw/2311595') as in_file:
     hex_data = in_file.read()
# Unhexlify the data.
bin_data = binascii.unhexlify(hex_data)
print(bin_data)
# Remove the embedded lengths.
jpeg_data = bin_data
# Write out the JPEG.
with open('out.jpg', 'wb') as out_file:
    out_file.write(jpeg_data)

已解决,这是更新的代码

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)
#r_data = "".unhexlify(chr(int(b_data[i:i+2],16)) for i in range(0, len(b_data),2))

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",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.png")

2 个答案:

答案 0 :(得分:16)

该图像不是由原始字节组成的 - 而是一个编码的JPEG文件。 此外,您没有将流的ascii HEX表示解析为正确的字节: 也就是说,该文件中的“ff”序列作为两个c字母“f”传递给PIL而不是一个数字为255的字节。

所以,首先,你将字符串解码为一个正确的字节序列 - 对于卷积感到遗憾 - 很可能有更好的方法来做到这一点,但我处于缓慢的一天:

data = urllib.urlopen("http://pastebin.ca/raw/2311595").read()
r_data = "".join(chr(int(data[i:i+2],16)) for i in range(0, len(data),2)) 
啊,C.Y。贴在评论上 - 这样:

>>> import binascii
>>> b_data = binascii.unhexlify(data)

现在,您将其作为JPEG图像导入PIL:

>>> from PIL import Image
>>> import cStringIO as StringIO
>>> stream = StringIO.StringIO(b_data)
>>> img = Image.open(stream)
>>> img.size
(320, 240)

答案 1 :(得分:1)

就像其他人所说的,Python 3最好使用io.BytesIO

import io
from PIL import Image

imageFileObj = open(imageFilename, "rb")
imageBinaryBytes = imageFileObj.read()
imageStream = io.BytesIO(imageBinaryBytes)
imageFile = Image.open(imageStream)
print("imageFile.size=%s" % imageFile.size)