[英]Python script to convert RBG image dataset into Grayscale images using pillow
[英]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.