from flask import Blueprint, send_file, jsonify, request from PIL import Image, ImageDraw, ImageFont import random import unicodedata import os import io import json api = Blueprint('apis', __name__, url_prefix='/api') 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) # 生成电话号码 def generate_phone_number(): # 随机生成手机号码的前缀 prefix = random.choice(['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152', '153', '155', '156', '157', '158', '159', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189']) # 随机生成手机号码的后缀 suffix = ''.join(random.choice(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) for _ in range(8)) # 将前缀和后缀组合起来,生成手机号码 return prefix + suffix @api.route('/avatars') def index(): name = request.args.get("name", '空值') han_char = '' # 待生成的字符串 if name == '空值': # 可以生成任意内容 han_char1 = get_random_common_char() han_char2 = get_random_common_char() han_char = han_char1 + han_char2 else: han_char = name[:2] # 生成图片 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') @api.route('/phone') def phone(): phone_number = generate_phone_number() phone = { 'phone': phone_number } return jsonify(phone)