使用 Flask 显示的图像错误或损坏
P粉299174094
P粉299174094 2023-09-12 00:21:51
0
1
719

我正在设置一个网络应用程序,我需要在其中显示一些图像。我从 API 收到的图像将 matplotlib 图转换为 png,然后使用 io 库将其发送到主 Web 应用程序。因此,我在页面上显示的图像几乎总是显示为不正确或错误。但如果我通过上下文菜单在新页面中打开它们,它们就可以了。

所以这段发送图的代码

@app.route('/send-data-a', methods=['GET'])
def send_data_user_dynamic():
...some code for diagram...
image_stream1 = io.BytesIO()
        plt.savefig(image_stream1, format='png')
        image_stream1.seek(0)
        plt.close(fig)

        return send_file(image_stream1, mimetype='image/png')

我尝试将时间戳放在主应用程序中,因此链接将是唯一的,但是没有帮助

@app.route('/data', methods=['GET'])
def data():
    timestamp = int(time.time())

    user_dynamic = requests.get(f'http://127.0.0.1:5000/send-data-a?timestamp={timestamp}')
    user_amount = requests.get(f'http://127.0.0.1:5000/send-data-b?timestamp={timestamp}')
    kp_month = requests.get(f'http://127.0.0.1:5000/send-data-c?timestamp={timestamp}')
    kp_week = requests.get(f'http://127.0.0.1:5000/send-data-d?timestamp={timestamp}')

    return render_template('second.html',
                           user_dynamic=user_dynamic.url,
                           user_amount=user_amount.url,
                           kp_month=kp_month.url,
                           kp_week=kp_week.url)
if __name__ == '__main__':
    app.run(debug=True, port=5001)

并且有一个 html 模板可以输出它们

<div class="diagram">
        <img src="{{ user_dynamic }}" alt="user_dynamic">
        <figcaption>some text</figcaption>
    </div>

P粉299174094
P粉299174094

全部回复(1)
P粉701491897
import base64

user_dynamic_response = requests.get('http://127.0.0.1:5000/send-data-a')
user_amount_response = requests.get('http://127.0.0.1:5000/send-data-b')
kp_month_response = requests.get('http://127.0.0.1:5000/send-data-c')
kp_week_response = requests.get('http://127.0.0.1:5000/send-data-d')

user_dynamic_image_data = base64.b64encode(user_dynamic_response.content).decode('utf-8')
user_amount_image_data = base64.b64encode(user_amount_response.content).decode('utf-8')
kp_month_image_data = base64.b64encode(kp_month_response.content).decode('utf-8')
kp_week_image_data = base64.b64encode(kp_week_response.content).decode('utf-8')

return render_template('second.html',
                       user_dynamic=user_dynamic_image_data,
                       user_amount=user_amount_image_data,
                       kp_month=kp_month_image_data,
                       kp_week=kp_week_image_data)

所以呃这段代码解决了问题

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板