python - 使用 PIL 绘制文本不适用于所有图像
问题描述
我正在尝试使用 PIL 在图像上绘制文本。但是,我只能在某些图像上看到文字。很多png都不起作用,比如这个:
http://r0k.us/graphics/kodak/kodim16.html
代码示例:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from os.path import expanduser
im1=Image.open(expanduser('~/Desktop/in.png'))
# Drawing the text on the picture
font = ImageFont.truetype('/Library/Fonts/Songti.ttc', 100)
draw = ImageDraw.Draw(im1)
draw.text((50, 600), 'OMG!', fill="#aa0000", font=font)
draw = ImageDraw.Draw(im1)
# Save the image with a new name
im1.save(expanduser('~/Desktop/out.png'))
我尝试添加.convert("RGBA")
和使用 RGB 作为颜色,但无济于事。
该代码适用于从我的 iPhone 拍摄的照片。但是,当我ImageMagick
将这些 iPhone 照片转换为 .jpg 或 .png 时,代码再次停止工作。
这个文本绘图功能是否仅适用于某些图像格式?
更新
我在通话中添加了实际的文本位置.text()
。该代码适用于从 iPhone 获取的 .png。
解决方案
我想你只是得到了x
和y
坐标错误的方式,并试图在一个 512 像素高的图像上写下 600 像素:
#!/usr/bin/env python3
import PIL
from PIL import Image, ImageFont, ImageDraw
im1=Image.open('start.png')
# Drawing the text on the picture
font = ImageFont.truetype('/Library/Fonts/Herculanum.ttf', 100)
draw = ImageDraw.Draw(im1)
draw.text((50, 200), 'OMG!', (255,0,255), font=font)
# Save the image with a new name
im1.save('result.png')
推荐阅读
- spring - Docker 容器未在浏览器上运行
- arrays - Int 数组在 c 中接受比声明大小多 1 个元素
- python - 保存到变量中时多行字符串不起作用
- vision - 如何通过 API 从我的 Google 相册中检索人物数据?
- c++ - 未使用计算的值,“如何解决警告”
- flutter - Dio.Post:具有不同 url 的多个 API 请求
- freemarker - JBake Freemarker 错误“这已评估为序列(包装器:ftSimpleSequence”
- flutter - Flutter 中 Futurebuilder 中的快照究竟意味着什么?
- java - PKIX 路径构建 - 通过 InvokeHTTP 处理器调用 API 时 NIFI 抛出错误
- node.js - 获取 Mongodb 数据到 Node 和 React