文字生图,遇到文字超出范围,字体警告,问了200个问题,gpt机器人 始终不能回答正确?

/data/user/0/org.qpython.qpy/files/bin/qpy thon3.sh "/storage/emulated/0/qpython/6. 33.py" && exit
/emulated/0/qpython/文6.33.py" && exit   < /storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 36825 (\N{CJK UNIFIED I DEOGRAPH-8FD9}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 26159 (\N{CJK UNIFIED I DEOGRAPH-662F}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 35201 (\N{CJK UNIFIED I DEOGRAPH-8981}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 22788 (\N{CJK UNIFIED I DEOGRAPH-5904}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 29702 (\N{CJK UNIFIED I DEOGRAPH-7406}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 30340 (\N{CJK UNIFIED I DEOGRAPH-7684}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 25991 (\N{CJK UNIFIED I DEOGRAPH-6587}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:43:  UserWarning: Glyph 23383 (\N{CJK UNIFIED I DEOGRAPH-5B57}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 36825 (\N{CJK UNIFIED I DEOGRAPH-8FD9}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 26159 (\N{CJK UNIFIED I DEOGRAPH-662F}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 35201 (\N{CJK UNIFIED I DEOGRAPH-8981}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 22788 (\N{CJK UNIFIED I DEOGRAPH-5904}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 29702 (\N{CJK UNIFIED I DEOGRAPH-7406}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 30340 (\N{CJK UNIFIED I DEOGRAPH-7684}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 25991 (\N{CJK UNIFIED I DEOGRAPH-6587}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:56:  UserWarning: Glyph 23383 (\N{CJK UNIFIED I DEOGRAPH-5B57}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 36825 (\N{CJK UNIFIED I DEOGRAPH-8FD9}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 26159 (\N{CJK UNIFIED I DEOGRAPH-662F}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 35201 (\N{CJK UNIFIED I DEOGRAPH-8981}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 22788 (\N{CJK UNIFIED I DEOGRAPH-5904}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 29702 (\N{CJK UNIFIED I DEOGRAPH-7406}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 30340 (\N{CJK UNIFIED I DEOGRAPH-7684}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 25991 (\N{CJK UNIFIED I DEOGRAPH-6587}) missing from current font.   plt.savefig(image_path)
/storage/emulated/0/qpython/6.33.py:69:  UserWarning: Glyph 23383 (\N{CJK UNIFIED I DEOGRAPH-5B57}) missing from current font.   plt.savefig(image_path)

#[QPython] Press enter to exit ...
/emulated/0/qpython/文6.3.py" && exit    < /storage/emulated/0/qpython/文6.3.py:34: D eprecationWarning: getsize is deprecated a nd will be removed in Pillow 10 (2023-07-0 1). Use getbbox or getlength instead.
  text_width, text_height = font.getsize(t ext)
操作完成!

#[QPython] Press enter to exit ...
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFil e.py", line 503, in _save
    fh = fp.fileno()
         ^^^^^^^^^
AttributeError: '_idat' object has no attr ibute 'fileno'

During handling of the above exception, an other exception occurred:

Traceback (most recent call last):
  File "/storage/emulated/0/qpython/文6.3. py", line 95, in <module>
    generate_text_image(word, font_path, i mage_path, background_color=(0, 0, 0), tex t_color=(255, 255, 255), font_size=24)
  File "/storage/emulated/0/qpython/文6.3. py", line 56, in generate_text_image
    image.save(output_path)
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/Image.py ", line 2353, in save
    save_handler(self, fp, filename)
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/PngImage Plugin.py", line 1397, in _save
    ImageFile._save(im, _idat(fp, chunk),  [("zip", (0, 0) + im.size, 0, rawmode)])
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFil e.py", line 507, in _save
    _encode_tile(im, fp, tile, bufsize, No ne, exc)
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFil e.py", line 518, in _encode_tile
    encoder.setimage(im.im, b)
SystemError: tile cannot extend outside im age
1|:/ $
/emulated/0/qpython/文6.2.py" && exit    < Traceback (most recent call last):
  File "/storage/emulated/0/qpython/文6.2. py", line 95, in <module>
    generate_text_image(word, font_path, i mage_path, background_color=(0, 0, 0), tex t_color=(255, 255, 255), font_size=24, fon t_weight="bold")
  File "/storage/emulated/0/qpython/文6.2. py", line 28, in generate_text_image
    font = ImageFont.truetype(font_path, f ont_size, weight=font_weight)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: truetype() got an unexpected ke yword argument 'weight'
1|:/ $

我的代码们。

import os
import matplotlib.pyplot as plt
import warnings

# 忽略警告
warnings.filterwarnings("ignore")

# 目录路径...
import os
from PIL import Image, ImageDraw, ImageFont

# 指定目录
font_directory = "/storage/emulated/0/文件/字体大全/"
output_directory = "/storage/emulated/0/文件/aidliux/文字图片/"

# 创建输出目录
if not os.path.exists(output_directory):
    os.makedirs(output_directory)

def process_text(text):
    # 分词
    words = text.split()

    # 标点符号替换为空格,然后分词
    punctuation_replaced = text.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ")
    words_punctuation = punctuation_replaced.split()

    # 长句子按照结构分割成短句
    sentences = text.split(". ")

    return words, words_punctuation, sentences

def generate_text_image(text, font_path, output_path, background_color=(0, 0, 0), text_color=(255, 255, 255), font_size=24):
    try:
        # 加载字体
        font = ImageFont.truetype(font_path, font_size, index=0)
    except OSError:
        print(f"字体文件 {font_path} 无法加载,已跳过处理。")
        return

    # 计算文本宽度和高度
    text_width, text_height = font.getsize(text)

    # 创建图片
    image_width = text_width + 20
    image_height = text_height + 20
    image = Image.new('RGB', (image_width, image_height), background_color)
    draw = ImageDraw.Draw(image)

    # 绘制文本
    draw.text((10, 10), text, font=font, fill=text_color)

    # 保存图片
    image.save(output_path)

# 遍历字体目录
for font_file in os.listdir(font_directory):
    font_path = os.path.join(font_directory, font_file)

    # 读取字体文件
    with open(font_path, 'rb') as f:
        font_data = f.read()

    # 对每个操作进行处理
    for i, operation in enumerate(["分词", "标点符号", "短句"]):
        # 创建操作对应的文件夹
        operation_directory = os.path.join(output_directory, operation)
        if not os.path.exists(operation_directory):
            os.makedirs(operation_directory)

        # 生成文本文件
        text = "Hello World"  # 替换为你需要处理的文本
        words, words_punctuation, sentences = process_text(text)
        file_name = operation + str(i + 1) + ".txt"
        file_path = os.path.join(operation_directory, file_name)
        with open(file_path, 'w') as f:
            if operation == "分词":
                f.write(" ".join(words))
            elif operation == "标点符号":
                f.write(" ".join(words_punctuation))
            elif operation == "短句":
                f.write(". ".join(sentences))

        # 生成文本图片
        image_directory = os.path.join(output_directory, "文字图片")
        if not os.path.exists(image_directory):
            os.makedirs(image_directory)

        for j, word in enumerate(words):
            image_name = f"{word}_黑底白字_{font_file}_{j + 1}.png"
            image_path = os.path.join(image_directory, image_name)

            generate_text_image(word, font_path, image_path, background_color=(0, 0, 0), text_color=(255, 255, 255), font_size=24)

print("操作完成!")
import os
from PIL import Image, ImageDraw, ImageFont

# 指定目录
font_directory = "/storage/emulated/0/文件/字体大全/"
output_directory = "/storage/emulated/0/文件/aidliux/文字图片/"

# 创建输出目录
if not os.path.exists(output_directory):
    os.makedirs(output_directory)

def process_text(text):
    # 分词
    words = text.split()

    # 标点符号替换为空格,然后分词
    punctuation_replaced = text.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ")
    words_punctuation = punctuation_replaced.split()

    # 长句子按照结构分割成短句
    sentences = text.split(". ")

    return words, words_punctuation, sentences

def generate_text_image(text, font_path, output_path, background_color=(0, 0, 0), text_color=(255, 255, 255), font_size=24, font_weight="bold"):
    try:
        # 加载字体
        font = ImageFont.truetype(font_path, font_size, weight=font_weight)
    except OSError:
        print(f"字体文件 {font_path} 无法加载,已跳过处理。")
        return

    # 计算文本宽度和高度
    text_width, text_height = font.getbbox(text)[:2]

    # 调整字体大小适应图片
    max_image_width = 500
    if text_width > max_image_width:
        font_size = int(font_size * max_image_width / text_width)
    font = ImageFont.truetype(font_path, font_size, weight=font_weight)

    # 创建图片
    image_width = int(text_width * 2)
    image_height = int(text_height * 2)
    image = Image.new('RGB', (image_width, image_height), background_color)
    draw = ImageDraw.Draw(image)

    # 计算文本绘制位置
    x = (image_width - text_width) // 2
    y = (image_height - text_height) // 2

    # 绘制文本
    draw.text((x, y), text, font=font, fill=text_color)

    # 保存图片
    image.save(output_path)

# 遍历字体目录
for font_file in os.listdir(font_directory):
    font_path = os.path.join(font_directory, font_file)

    # 读取字体文件
    with open(font_path, 'rb') as f:
        font_data = f.read()

    # 对每个操作进行处理
    for i, operation in enumerate(["分词", "标点符号", "短句"]):
        # 创建操作对应的文件夹
        operation_directory = os.path.join(output_directory, operation)
        if not os.path.exists(operation_directory):
            os.makedirs(operation_directory)

        # 生成文本文件
        text = "Hello World"  # 替换为你需要处理的文本
        words, words_punctuation, sentences = process_text(text)
        file_name = operation + str(i + 1) + ".txt"
        file_path = os.path.join(operation_directory, file_name)
        with open(file_path, 'w') as f:
            if operation == "分词":
                f.write(" ".join(words))
            elif operation == "标点符号":
                f.write(" ".join(words_punctuation))
            elif operation == "短句":
                f.write(". ".join(sentences))

        # 生成文本图片
        image_directory = os.path.join(output_directory, "文字图片")
        if not os.path.exists(image_directory):
            os.makedirs(image_directory)

        for j, word in enumerate(words):
            image_name = word + " 黑底白字 " + font_file + str(j + 1) + ".png"
            image_path = os.path.join(image_directory, image_name)

            generate_text_image(word, font_path, image_path, background_color=(0, 0, 0), text_color=(255, 255, 255), font_size=24, font_weight="bold")

print("操作完成!")
/storage/emulated/0/文件/字体大全/
这个目录下有所有字体
遍历所有字体
对input输入的文字,分别进行3种操作分支
1 分词
2 标点符号替换空格,而后分词
3. 长句子按照结构弄成短句

分别生成各自的文件夹下
文件夹名分别为
分词   标点符号  短句
储存为txt txt文件名命名方式为刚刚生成的文件夹名+数字编号

然后,黑底白字,对每个词语生成各自图片
存储在相信的文件夹里
图片命名规则
图片中的词语+空格(黑底白字)+图片中用的字体名+序号

【相关推荐】




如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^