You need to enable JavaScript to run this app. 使用PIL/Pillow添加并旋转45度文本遇问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用PIL/Pillow添加并旋转45度文本遇问题求助

解决PIL/Pillow添加并旋转45度文本的问题

问题1:使用ImageFont.TransposedFont时提示Image.ROTATE_90不存在

Image.ROTATE_90是旧版PIL的常量,新版Pillow已将其移除,可直接用对应整数值替代,或使用Image.Transpose枚举。同时原代码的坐标逻辑需调整,避免旋转后文本超出画布。

修正后的代码:

from PIL import Image, ImageDraw, ImageFont

image = Image.open("good_watermark.jpg")
width, height = image.size

font = ImageFont.truetype("arial.ttf", 25)
# 用整数2替代Image.ROTATE_90(对应90度旋转)
font = ImageFont.TransposedFont(font, orientation=2)

drawer = ImageDraw.Draw(image)
# 调整坐标适配旋转后的文本尺寸
drawer.text((width/3, height/2), "@channel", font=font, fill='black')

image.save('new_img.jpg')
image.show()

问题2:创建透明文本图像粘贴后主图不显示文本

原代码存在三个核心问题:未显式指定文本颜色、旋转时未保留完整文本区域、初始坐标可能导致文本超出画布。

修正后的代码:

from PIL import Image, ImageDraw, ImageFont

background_image = Image.open("white_img.jpeg")
width, height = background_image.size

# 创建与背景同尺寸的透明文本层
text_image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(text_image)

font = ImageFont.truetype("arial.ttf", 40)
# 显式指定文本颜色,同时调整初始坐标
draw.text((width/4, height/4), "TEXT", font=font, fill='black')

# 旋转时添加expand=True,避免文本被裁剪
rotated_text_image = text_image.rotate(45, expand=True)

# 计算居中粘贴的坐标(可选)
paste_x = (width - rotated_text_image.width) // 2
paste_y = (height - rotated_text_image.height) // 2

# 粘贴文本层,使用自身alpha通道作为遮罩
background_image.paste(rotated_text_image, (paste_x, paste_y), mask=rotated_text_image)

background_image.save("new_img.jpg")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:32:19