matplotlib에서 flask로 이미지 생성

10652 단어 Flask
  • matlot.json
  • {
      " ": 15260,
      " ": 12586,
      " ": 13305,
      " ": 9000,
      " ": 16060,
      " ": 14010,
      " ": 8000,
      " ": 7800,
      " ": 8500
    }
    
  • func.py
  • import json
    
    
    def json_to_dict(filename):
        json_file = open(filename, 'r', encoding='utf-8')
        return json.loads(json_file.read())
    
  • views.py
  • from . import matlot
    from matplotlib.pylab import *
    from flask import render_template
    from io import BytesIO
    from .func import json_to_dict, ax
    import base64
    
    def json_img(data):
        font = {'family': 'SimHei',
                'weight': 'bold',
                'size': '14'}
        rc('font', **font)  #  
        rc('axes', unicode_minus=False)
        rcParams['savefig.dpi'] = 100  #  
    
        for x, y in data.items():
            bar(x, y, align='center')   #  
            text(x, y + 100, '%.2f' % y, ha='center', va='bottom', size=10, color="#909299") #  
    
        #  ,py3 BytesIO()
        img = BytesIO()
        savefig(img, format='png')
        img.seek(0)
        # img base64 
        img_base64 = base64.b64encode(img.getvalue()).decode('utf8')
    
        #  , 
        ax = gca()
        ax.spines['right'].set_color('none') #  
        ax.spines['top'].set_color('none') #  
        ax.xaxis.set_ticks_position('bottom')
        ax.spines['bottom'].set_position(('data',0)) #  0 
        
        return img_base64
    
    
    @matlot.route('/')
    def fig():
        data = json_to_dict('./file/matlot.json')
        # print(data)
        # return send_file(json_img(data), mimetype='image/png')
        return render_template('fig.html',img_base64=json_img(data))
    

    좋은 웹페이지 즐겨찾기