随机颜色封面生成

功能说明:在16:9白色背景为底的图片上水平,上下居中绘制
修改于:2024-03-29
# 1、对输入文字随机颜色进行绘制

~~~ python
import random
from PIL import Image, ImageDraw, ImageFont


def check_char_type(char):
    if char.isdigit():
        return "数字"
    elif char.isalpha():
        if ord(char) >= 0x4e00 and ord(char) <= 0x9fff:
            return "汉字"
        else:
            return "英文字符"
    else:
        return "其他字符"

# 利用重叠继续加粗
def draw_text(draw, text, font, position, color, bold_color, align):
    draw.text((position[0] + 1, position[1]), text, font=font, fill=bold_color, align=align)
    draw.text((position[0], position[1] + 1), text, font=font, fill=bold_color, align=align)
    draw.text(position, text, font=font, fill=color, align=align)


def draw_img(text, width=356, height=200): # 16:9
    atext = text
    # 获取要写入的文字
    gradient_colors = [(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for _ in
                       range(len(text))]
    # 创建白色背景图片
    image = Image.new('RGB', (width, height), 'white')

    # 获取字体
    font = ImageFont.truetype('STCAIYUN.TTF', 32)
    # 计算文字大小和位置
    text_width, text_height = ImageDraw.Draw(image).textsize(text, font)
    x = (width - (32 * len(text)) - 5) // 2
    y = (height // 2) - 25

    # 在图片中央水平对齐加粗写入文字
    draw = ImageDraw.Draw(image)

    last_x = x
    for i, text in enumerate(text):
        draw_text(draw, text, font, (last_x, y), gradient_colors[i], gradient_colors[i], align='center')
        textType = check_char_type(text)
        print(i, textType)
        if textType == '数字':
            last_x += 25
        elif textType == '汉字':
            last_x += 36
        elif textType == '英文字符':
            if text in ['i', 'I']:
                last_x += 14
            elif text in ['m']:
                last_x += 27
            else:
                last_x += 21
        else:
            last_x += 10
    # 保存图片
    image.show()
    image.save(f'{atext.replace(" ", "").strip()}.png')


draw_img('某盾空间推理点选')

字体文件:STCAIYUN.TTF