栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用PIL在其中绘制矩形和文本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用PIL在其中绘制矩形和文本

你可以不用

composite()

from PIL import Image, ImageFont, ImageDraw, ImageEnhancesource_img = Image.open(file_name).convert("RGBA")draw = ImageDraw.Draw(source_img)draw.rectangle(((0, 00), (100, 100)), fill="black")draw.text((20, 70), "something123", font=ImageFont.truetype("font_path123"))source_img.save(out_file, "JPEG")

您可以创建带有按钮大小的空图像,并在其上放置文本,然后再将该图像放置在上

source_img
。这样,长文本将被剪切为按钮的大小。

from PIL import Image, ImageFont, ImageDraw, ImageEnhancesource_img = Image.open("source.jpg").convert("RGBA")# create image with size (100,100) and black backgroundbutton_img = Image.new('RGBA', (100,100), "black")# put text on imagebutton_draw = ImageDraw.Draw(button_img)button_draw.text((20, 70), "very loooooooooooooooooong text", font=ImageFont.truetype("arial"))# put button on source image in position (0, 0)source_img.paste(button_img, (0, 0))# save in new filesource_img.save("output.jpg", "JPEG")

编辑:

ImageFont.getsize(text)
用来获取文本大小并创建具有正确大小的按钮。

from PIL import Image, ImageFont, ImageDraw, ImageEnhancesource_img = Image.open("input.jpg").convert("RGBA")font = ImageFont.truetype("arial")text = "very loooooooooooooooooong text"# get text sizetext_size = font.getsize(text)# set button size + 10px marginsbutton_size = (text_size[0]+20, text_size[1]+20)# create image with correct size and black backgroundbutton_img = Image.new('RGBA', button_size, "black")# put text on button with 10px marginsbutton_draw = ImageDraw.Draw(button_img)button_draw.text((10, 10), text, font=font)# put button on source image in position (0, 0)source_img.paste(button_img, (0, 0))# save in new filesource_img.save("output.jpg", "JPEG")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号