简体   繁体   中英

Convert Pillow grayscale image to hexadecimal value?

I'm creating an image with Pillow as follows:

from PIL import Image, ImageDraw, ImageFont
import textwrap
from io import BytesIO

def _font_as_bytes(style):
    with open(f'myfont_{style}.ttf', 'rb') as f:
        font_bytes = BytesIO(f.read())
    return font_bytes

font_title = ImageFont.truetype(_font_as_bytes('bold'), 30)
font_subtitle = ImageFont.truetype(_font_as_bytes('bold'), 18)
font_body = ImageFont.truetype(_font_as_bytes('regular'), 14)

img = Image.new("1", (296,128), color=255)

d = ImageDraw.Draw(img)

d.text((10,5), "Lorem Ipsum", font=font_title, fill=0)

subtitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer tristique euismod elit, ac porttitor arcu tempus at.'

offset = 40
for line in textwrap.wrap(subtitle, width=33):
    d.text((10, offset), line, font=font_subtitle, fill=0)
    offset += font_subtitle.getsize(line)[1]

for line in textwrap.wrap(body, width=45):
    d.text((10, offset), line, font=font_body, fill=0)
    offset += font_body.getsize(line)[1]

An img.show() outputs the desired result ( although I'm not really satisfied with the rendering of the letters, not sure why they don't look smooth ):

But when I try to get the hexadecimal values of the image, by doing:

output = BytesIO()
img.save(output, format='BMP')
hex_data = output.getvalue()
print(hex_data)

I get an output starting with "BM" and signs like { or ? along with hex values, when I was expecting only hex values.

Sending that output to an e-paper display adds a translation to the image like this:

I guess I'm not getting the hex values right, has anyone any idea on how to do this?

I ended up resolving this issue by adding:

from PIL import ImageChops
img = ImageChops.offset(img, 0, 10)

right before saving to the buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM