from flask import Blueprint, send_file from PIL import Image, ImageDraw, ImageFont import random import unicodedata import os import io api = Blueprint('apis', __name__, url_prefix='/api') @api.route('/avatars') def index(): app_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) static_path = os.path.join(app_root, 'static') # 生成随机汉字 def get_random_common_char(): # 读取文件中的常用汉字 with open(os.path.join(static_path, 'demo.txt'), 'r', encoding='utf-8') as f: common_chars = f.read() # 去除空格 common_chars = common_chars.replace(' ', '') common_chars = common_chars.strip() # 创建字符映射表 translator = {ord(c): None for c in common_chars if unicodedata.category(c).startswith('P')} # 使用字符映射表去除标点符号 s = common_chars.translate(translator) return random.choice(s) # 可以生成任意内容 han_char1 = get_random_common_char() han_char2 = get_random_common_char() han_char = han_char1 + han_char2 # 生成图片 image = Image.new('RGB', (64, 64), (255, 255, 255)) draw = ImageDraw.Draw(image) font = ImageFont.truetype(os.path.join(static_path, 'font/msyh.ttf'), 28) # 绘制一个圆形 # 正方形的中心坐标 x = 32.0 y = 32.0 # 正方形的边长 length = 62.0 # 计算半径 r = length / 2 # 计算圆的左上角和右下角的坐标 left = x - r top = y - r right = x + r bottom = y + r draw.ellipse((left, top, right, bottom), fill=(0, 129, 255)) draw.text((4, 12), han_char, font=font, fill=(255, 255, 255)) # 将图像转换成字节流 buf = io.BytesIO() image.save(buf, format='png') buf.seek(0) return send_file(buf, mimetype='image/png')