繁体   English   中英

将枕头灰度图像转换为十六进制值?

[英]Convert Pillow grayscale image to hexadecimal value?

我正在用 Pillow 创建一个图像,如下所示:

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]

img.show()输出所需的结果(虽然我对字母的渲染并不满意,不知道为什么它们看起来不平滑):

但是当我尝试通过执行以下操作获取图像的十六进制值时:

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

我得到一个 output 以“BM”开头并带有{? 与十六进制值一起,当我只期望十六进制值时。

将 output 发送到电子纸显示器会为图像添加翻译,如下所示:

我想我没有得到正确的十六进制值,有人知道如何做到这一点吗?

我最终通过添加解决了这个问题:

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

在保存到缓冲区之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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