from PIL import Image, text into pictures, ImageFont import jieba word segmentation, input elegant python to draw pictures

start code

import os
from PIL import Image, ImageDraw, ImageFont
import jieba

def generate_image_with_white_bg(text, font_path, output_path):
    # 设置图片大小和背景颜色
    image_width = 800
    image_height = 600
    bg_color = (255, 255, 255)  # 白色

    # 创建图片对象
    image = Image.new("RGB", (image_width, image_height), bg_color)
    draw = ImageDraw.Draw(image)

    # 设置字体和字体大小
    font_size = 36
    font = ImageFont.truetype(font_path, font_size)

    # 将文本按行分割
    lines = text.split("\n")

    # 绘制文本
    y = 50  # 初始纵坐标
    for line in lines:
        words = jieba.lcut(line)  # 分词去重
        for word in words:
            word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格
            draw.text((50, y), word, fill=(0, 0, 0), font=font)  # 绘制文本
            y += 50  # 纵坐标递增

    # 保存图片
    image.save(output_path)

def generate_image_with_black_bg(text, font_path, output_path):
    # 设置图片大小和背景颜色
    image_width = 800
    image_height = 600
    bg_color = (0, 0, 0)  # 黑色

    # 创建图片对象
    image = Image.new("RGB", (image_width, image_height), bg_color)
    draw = ImageDraw.Draw(image)

    # 设置字体和字体大小
    font_size = 36
    font = ImageFont.truetype(font_path, font_size)

    # 将文本按行分割
    lines = text.split("\n")

    # 绘制文本
    y = 50  # 初始纵坐标
    for line in lines:
        words = jieba.lcut(line)  # 分词去重
        for word in words:
            word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格
            draw.text((50, y), word, fill=(255, 255, 255), font=font)  # 绘制文本
            y += 50  # 纵坐标递增

    # 保存图片
    image.save(output_path)

def main():
    # 输入文本内容
    print("请输入多行文本内容,以空行结束:")
    text = ""
    while True:
        line = input()
        if line == "":
            break
        text += line + "\n"

    # 创建保存路径
    save_path = "/storage/emulated/0/文件/aidliux/生成图片/"
    os.makedirs(save_path, exist_ok=True)

    # 生成白底黑字宋体图片
    default_font_path = "path_to_default_font.ttf"  # 将此处替换为安卓默认字体文件路径
    white_bg_output_path = os.path.join(save_path, "white_bg_simsun.jpg")
    generate_image_with_white_bg(text, default_font_path, white_bg_output_path)

    # 生成黑底白字宋体图片
    black_bg_output_path = os.path.join(save_path, "black_bg_simsun.jpg")
    generate_image_with_black_bg(text, default_font_path, black_bg_output_path)

    print("白底黑字宋体图片已生成,保存路径为:{}".format(white_bg_output_path))
    print("黑底白字宋体图片已生成,保存路径为:{}".format(black_bg_output_path))

if __name__ == "__main__":
    main()

Running results

/data/user/0/org.qpython.qpy/files/bin/qpy thon3.sh "/storage/emulated/0/qpython/表格 操作行列1.2.5.6.5.文字成图.py" && exit
作行列1.2.5.6.5.文字成图.py" && exit     < 请输入多行文本内容,以空行结束:
优雅之美

Traceback (most recent call last):
  File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 90, in  <module>
    main()
  File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 80, in  main
    generate_image_with_white_bg(text, def ault_font_path, white_bg_output_path)
  File "/storage/emulated/0/qpython/表格操 作行列1.2.5.6.5.文字成图.py", line 17, in  generate_image_with_white_bg
    font = ImageFont.truetype(font_path, f ont_size)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 976, in truetype
    return freetype(font)
           ^^^^^^^^^^^^^^
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 973, in freetype
    return FreeTypeFont(font, size, index,  encoding, layout_engine)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/user/0/org.qpython.qpy/files /lib/python3.11/site-packages/PIL/ImageFon t.py", line 249, in __init__
    self.font = core.getfont(
                ^^^^^^^^^^^^^
OSError: cannot open resource
1|:/ $
1|:/ $

Error ❌print

This error is caused by missing font files. In the code, you need to replace default_font_paththe variable with the default font file path on the Android device.

You can follow these steps to resolve this issue:

1. Find the default font file path on your Android device. Typically, they are located /system/fonts/in directories and may have filenames such as DroidSans.ttf, , NotoSansCJK-Regular.ttcetc. You can use a file manager or terminal to find it.

2. Replace the found default font file path into default_font_paththe variable in your code. For example, assuming the path found is /system/fonts/DroidSans.ttf, the code should be replaced with default_font_path = "/system/fonts/DroidSans.ttf".

After completing the above steps, run the code again and the image should be generated normally.

We've added some improved methods

文件名命名方法:编号. 词语 时间戳
保存 /storage/emulated/0/文件/代码print相关/结构图/
没有就新建
中文字体 /storage/emulated/0/文件/字体大全/字体包/宋体.ttf
其它中文字体 /storage/emulated/0/文件/字体大全/字体包/
英语字体 /storage/emulated/0/文件/字体大全/
这个目录下检索可用英语.ttf,如果需要英语的话
文件名没有库或者样式就省略掉

improved code

This code is relatively long, you can update your program as follows:

import os
import time
from PIL import Image, ImageDraw, ImageFont
import jieba

def generate_image_with_white_bg(text, font_path, output_path):
    # 设置图片大小和背景颜色
    image_width = 800
    image_height = 600
    bg_color = (255, 255, 255)  # 白色

    # 创建图片对象
    image = Image.new("RGB", (image_width, image_height), bg_color)
    draw = ImageDraw.Draw(image)

    # 设置字体和字体大小
    font_size = 36
    font = ImageFont.truetype(font_path, font_size)

    # 将文本按行分割
    lines = text.split("\n")

    # 绘制文本
    y = 50  # 初始纵坐标
    for line in lines:
        words = jieba.lcut(line)  # 分词去重
        for word in words:
            word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格
            draw.text((50, y), word, fill=(0, 0, 0), font=font)  # 绘制文本
            y += 50  # 纵坐标递增

    # 保存图片
    image.save(output_path)

def generate_image_with_black_bg(text, font_path, output_path):
    # 设置图片大小和背景颜色
    image_width = 800
    image_height = 600
    bg_color = (0, 0, 0)  # 黑色

    # 创建图片对象
    image = Image.new("RGB", (image_width, image_height), bg_color)
    draw = ImageDraw.Draw(image)

    # 设置字体和字体大小
    font_size = 36
    font = ImageFont.truetype(font_path, font_size)

    # 将文本按行分割
    lines = text.split("\n")

    # 绘制文本
    y = 50  # 初始纵坐标
    for line in lines:
        words = jieba.lcut(line)  # 分词去重
        for word in words:
            word = word.replace(",", " ").replace("。", " ").replace("?", " ")  # 替换标点符号为空格
            draw.text((50, y), word, fill=(255, 255, 255), font=font)  # 绘制文本
            y += 50  # 纵坐标递增

    # 保存图片
    image.save(output_path)

def main():
    # 输入文本内容
    print("请输入多行文本内容,以空行结束:")
    text = ""
    while True:
        line = input()
        if line == "":
            break
        text += line + "\n"

    # 创建保存路径
    output_dir = "/storage/emulated/0/文件/代码print相关/结构图/"
    os.makedirs(output_dir, exist_ok=True)

    # 初始化时间戳
    timestamp = int(time.time())

    # 获取中文字体路径
    chinese_font_path = "/storage/emulated/0/文件/字体大全/字体包/宋体.ttf"

    # 获取英文字体路径
    english_font_path = None
    english_fonts_dir = "/storage/emulated/0/文件/字体大全/"
    for filename in os.listdir(english_fonts_dir):
        if filename.endswith(".ttf"):
            english_font_path = os.path.join(english_fonts_dir, filename)
            break

    # 生成白底黑字宋体图片
    white_bg_output_path = os.path.join(output_dir, "{}.{}.jpg".format(len(text), timestamp))
    generate_image_with_white_bg(text, chinese_font_path, white_bg_output_path)

    # 生成黑底白字宋体图片
    black_bg_output_path = os.path.join(output_dir, "{}.{}.jpg".format(len(text), timestamp))
    generate_image_with_black_bg(text, chinese_font_path, black_bg_output_path)

    print("白底黑字宋体图片已生成,保存路径为:{}".format(white_bg_output_path))
    print("黑底白字宋体图片已生成,保存路径为:{}".format(black_bg_output_path))

    if english_font_path is not None:
        # 生成白底黑字英语图片
        white_bg_output_path = os.path.join(output_dir, "{}e.{}.jpg".format(len(text), timestamp))
        generate_image_with_white_bg(text, english_font_path, white_bg_output_path)

        # 生成黑底白字英语图片
        black_bg_output_path = os.path.join(output_dir, "{}e.{}.jpg".format(len(text), timestamp))
        generate_image_with_black_bg(text, english_font_path, black_bg_output_path)

        print("白底黑字英语图片已生成,保存路径为:{}".format(white_bg_output_path))
        print("黑底白字英语图片已生成,保存路径为:{}".format(black_bg_output_path))

if __name__ == "__main__":
    main()

This program will generate 4 pictures based on the input text, namely a white background with black characters in Song font, a black background with white characters in Song font, a white background with black characters in English, and a black background with white characters in English. Among them, the Chinese font is used /storage/emulated/0/文件/字体大全/字体包/宋体.ttf, and the English font is /storage/emulated/0/文件/字体大全/the first file found in the directory .ttfas the default font. The saving path is /storage/emulated/0/文件/代码print相关/结构图/, and the file name format is 编号. 词语 时间戳.jpg. If there is no corresponding library or style, it will be omitted, for example, if there is only number and timestamp.

Please note that English fonts may appear garbled in Chinese text and need to be adjusted according to the actual situation.

result

Insert image description here
Let's see if there is this file. You can see only the two generated pictures.
Insert image description here
This is basically a prototype for me. The front is typed in Chinese. There are really many fonts in
Insert image description here
my font folder . Currently, it is possible faint.
Insert image description here
This is played in English, which is 2 frames plus 2 XX . You can see that there are two playing cards!

Guess you like

Origin blog.csdn.net/weixin_73675558/article/details/133522884