123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- # coding=utf-8
- import flask
- import imgkit
- import json
- import os
- import oss2
- import random
- from flask import request
- # 创建一个服务,把当前这个python文件当做一个服务
- server = flask.Flask(__name__)
- # 端口配置
- port = 5008
- host = '127.0.0.1'
- debug = True
- # 工具配置
- tool_path = r'/usr/local/bin/wkhtmltoimage'
- # tool_path = r'E:\wkhtmltopdf\bin\wkhtmltoimage.exe'
- # OSS配置
- oss_end_point = 'oss-cn-shanghai.aliyuncs.com'
- oss_bucket = 'hzchart'
- oss_key_id = 'LTAIFMZYQhS2BTvW'
- oss_key_secret = '12kk1ptCHoGWedhBnKRVW5hRJzq9Fq'
- resource_host = 'https://hzstatic.hzinsights.com/'
- # server.config['JSON_AS_ASCII'] = False
- # @server.route()可以将普通函数转变为服务 登录接口的路径、请求方式
- @server.route('/htm2img', methods=['post'])
- def htm2img():
- # 获取参数
- req_data = request.get_json()
- if req_data is None:
- return json.dumps({'code': 5004, 'msg': '参数有误', 'data': ''}, ensure_ascii=False)
- # 参数校验
- contents = req_data['html_content']
- if contents is None or contents == '':
- return json.dumps({'code': 5004, 'msg': '获取html文本内容失败', 'data': ''}, ensure_ascii=False)
- width = req_data['width']
- if width <= 0:
- return json.dumps({'code': 5004, 'msg': '图片宽度有误', 'data': ''}, ensure_ascii=False)
- height = req_data['height']
- if height <= 0:
- return json.dumps({'code': 5004, 'msg': '图片长度有误', 'data': ''}, ensure_ascii=False)
- # 生成html文件
- rand_name = get_rand_string()
- html_path = 'html/' + rand_name + '.html'
- res = html2file(contents, html_path)
- if not res:
- return json.dumps({'code': 5004, 'msg': '生成html失败', 'data': ''}, ensure_ascii=False)
- # html转图片
- img_name = rand_name + '.jpg'
- img_path = html_to_img(html_path, img_name, width, height)
- if img_path == '':
- return json.dumps({'code': 400, 'msg': '生成图片失败', 'data': ''}, ensure_ascii=False)
- # 上传OSS
- upload_dir = 'static/images/yb/htm2img/'
- save_path = upload_dir + img_name
- upload_res = upload_oss_file(save_path, img_path)
- # 清除本地生成的html及图片
- clear_local_file(img_path, html_path)
- if upload_res.status == 200:
- resource_url = resource_host + save_path
- return json.dumps({'code': 200, 'msg': '生成图片成功', 'data': resource_url}, ensure_ascii=False)
- else:
- return json.dumps({'code': 400, 'msg': '生成图片失败', 'data': ''}, ensure_ascii=False)
- # html文件转为图片
- def html_to_img(html_url, img_name, width=100, height=100):
- path_wkimg = tool_path # 工具路径
- cfg = imgkit.config(wkhtmltoimage=path_wkimg)
- opt = {"width": width, "height": height, "quality": 100, "format": "jpg"}
- img_path = 'img/' + img_name
- imgkit.from_file(html_url, img_path, config=cfg, options=opt)
- try:
- os.path.isfile(img_path)
- return img_path
- except Exception as e:
- # print(e)
- return ''
- # 上传图片至OSS
- def upload_oss_file(save_path, file_path):
- auth = oss2.Auth(oss_key_id, oss_key_secret)
- bucket = oss2.Bucket(auth, oss_end_point, oss_bucket)
- return bucket.put_object_from_file(save_path, file_path)
- # 生成指定长度的随机字符串
- def get_rand_string(size=28):
- random_str = ''
- base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
- length = len(base_str) - 1
- for i in range(size):
- random_str += base_str[random.randint(0, length)]
- return random_str
- # 清除本地生成的文件
- def clear_local_file(img_path, html_path):
- try:
- os.remove(img_path)
- os.remove(html_path)
- return True
- except OSError as e:
- # print(e)
- return False
- # html文本生成文件
- def html2file(content, file_path):
- try:
- f = open(file_path, 'w', encoding='UTF-8')
- f.write(content)
- f.close()
- return True
- except Exception as e:
- # print(e)
- return False
- if __name__ == '__main__':
- server.run(debug=debug, port=port, host=host)
|