You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Wand实现文本拉伸绘制:适配指定区域

使用Python Wand实现文本拉伸适配指定区域并生成1位BMP图像

解决方案代码

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

imagewidth = 1800
imageheight = 600

def makeImage(mynr):
    # 创建临时透明画布绘制文本,确保文本完整显示
    temp_text = Image(width=imagewidth, height=imageheight, background=Color("transparent"))
    with Drawing() as draw:
        draw.font = "Arial"
        draw.font_size = 500
        draw.gravity = "center"
        draw.fill_color = Color("black")
        draw.text(0, 0, f"{mynr:04d}")
        draw(temp_text)
    
    # 裁剪掉文本周围的空白区域,获取文本实际大小
    temp_text.trim()
    
    # 将文本图像拉伸至目标画布尺寸
    with temp_text.clone() as stretched_text:
        stretched_text.resize(width=imagewidth, height=imageheight)
        
        # 创建白色背景的目标图像,合成拉伸后的文本
        myimage = Image(width=imagewidth, height=imageheight, background=Color("white"))
        myimage.composite(stretched_text, left=0, top=0)
        
        # 转换为1位黑白BMP格式
        myimage.depth = 1
        myimage.type = "bilevel"
        
        myimage.save(filename=f'test{mynr:02d}.bmp')
        print(mynr)  # 打印进度

def do_numbers():
    for i in range(30):
        makeImage(i+1)

if __name__ == "__main__":
    do_numbers()

关键步骤说明

  • 临时画布绘制文本:用透明背景创建临时画布,避免背景干扰后续裁剪操作,确保文本完整绘制。
  • 裁剪空白区域:通过trim()自动去除文本周围的透明空白,得到仅包含文本的最小图像,为后续拉伸提供准确的文本区域。
  • 拉伸文本适配边界:使用resize()将裁剪后的文本图像拉伸到目标画布的宽高,实现文本完全适配指定区域的效果。
  • 合成到白色背景:创建白色背景的最终画布,将拉伸后的文本合成到左上角,确保覆盖整个画布。
  • 转换为1位BMP:设置depth=1和type="bilevel",生成符合要求的1位黑白位图格式。

内容的提问来源于stack exchange,提问作者MyICQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:38:09