index.py 2.6 KB
Newer Older
梦想橡皮擦's avatar
梦想橡皮擦 已提交
1
from flask import Blueprint, send_file, jsonify
梦想橡皮擦's avatar
梦想橡皮擦 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

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')
梦想橡皮擦's avatar
梦想橡皮擦 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85


@api.route('/phone')
def phone():
    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

    phone_number = generate_phone_number()
    phone = {
        'phone': phone_number
    }

    return jsonify(phone)