将matplotlib映像发送到pymsteams(无法创建新标签pymsteams) [英] Sending matplotlib image to pymsteams (cannot create new tag pymsteams)
本文介绍了将matplotlib映像发送到pymsteams(无法创建新标签pymsteams)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用matplotlib绘制图像.
I am using matplotlib to plot my image.
import pandas as pd
from matplotlib import pyplot as plt
x = ['09:30', '09:33', '09:40', '09:43', '09:50', '09:53', '10:00', '10:03', '10:10', '10:13']
y = ['3010.910000', '3011.650000', '3009.130000', '3011.500000', '3010.460000', '3010.950000', '3012.830000', '3013.120000', '3011.730000', '3010.130000']
matrix = pd.DataFrame({'Time': x, 'Quote': y})
matrix['Quote'] = matrix['Quote'].astype(float)
plt.plot('Time', 'Quote', data=matrix, color='mediumvioletred')
这是现在的挑战:
import pymsteams
web_hook = 'My Microsoft Teams URL https://outlook.office.com/webhook/blahblah'
teams_message = pymsteams.connectorcard(web_hook)
msg_section = pymsteams.cardsection()
msg_section.title('Title')
msg_section.addImage(image) #I want to add that plt image here
teams_message.addSection(msg_section)
teams_message.text("Some Message")
self.teams_message.send()
我已经尝试过这个(我想要这种方法,使用缓存):
I have tried this (and I want this approach, using cache):
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
msg_section.addImage(buf.read())
我确实尝试将图像保存到本地驱动器c:/temp/".该代码没有给出任何错误消息,但Teams上的图像为空白图像,即使该图像在c:/temp中是正确的
I did try saving the image to local drive 'c:/temp/'. The code did not give any error msg, but the image on Teams was a blank image, even though the image is correct in c:/temp
推荐答案
总结.PNG图片必须转换为base64字符串.
In summary. A PNG image has to be converted to base64 string.
请看下面的例子.
请注意,我使用的是 Python 3.6.
此外,连接器卡中的图像宽度似乎受到限制.
Note that I'm using Python 3.6.
Additionally image width seems to be limited in a Connector Card.
import numpy as np
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import pymsteams
# generate fig
fig, ax = plt.subplots(1,1,figsize=(20,6))
ax.hist(np.random.normal(0, 1, 1000), bins=51, edgecolor='k', alpha=0.5);
buf = BytesIO()
fig.savefig(buf, format="png")
# get base64 string
data = base64.b64encode(buf.getbuffer()).decode("ascii")
encoded_fig = f"data:image/png;base64,{data}"
# send encoded_fig via webhook
web_hook = 'YOUR_WEBHOOK'
teams_message = pymsteams.connectorcard(web_hook)
msg_section = pymsteams.cardsection()
msg_section.title('Title')
msg_section.addImage(encoded_fig) #I want to add that plt image here
teams_message.addSection(msg_section)
teams_message.text("Some Message")
teams_message.send()
这篇关于将matplotlib映像发送到pymsteams(无法创建新标签pymsteams)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文