Browse Source

html转图片

hsun 1 year ago
parent
commit
4451153a8e
2 changed files with 145 additions and 0 deletions
  1. 133 0
      html2img/main.py
  2. 12 0
      html2img/工具说明.txt

+ 133 - 0
html2img/main.py

@@ -0,0 +1,133 @@
+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'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)

+ 12 - 0
html2img/工具说明.txt

@@ -0,0 +1,12 @@
+# 工具安装
+	https://wkhtmltopdf.org/downloads.html
+# 工具测试
+	https://blog.csdn.net/weixin_45019350/article/details/115799676
+
+# flask部署参考
+	https://blog.csdn.net/qq_50258800/article/details/108164175
+	https://blog.csdn.net/qq_43580193/article/details/118523117
+
+# main.py配置修改
+	main.py:12	端口配置
+	main.py:18	工具path