我正在尝试使用 Discord API 创建一个机器人,该机器人将获取用户的有效 LaTeX 输入,将 LaTeX 转换为 PNG,然后将该 PNG 上传到服务器。由于一些谷歌搜索,我有一些代码可以生成 LaTeX PNG,但我被困在上传步骤上。
def plot_equation(eq, fontsize=50, outfile=None, padding=0.1, **kwargs):
"""Plot an equation as a matplotlib figure.
Parameters
----------
eq : string
The equation that you wish to plot. Should be plottable with
latex. If `$` is included, they will be stripped.
fontsize : number
The fontsize passed to plt.text()
outfile : string
Name of the file to save the figure to.
padding : float
Amount of padding around the equation in inches.
Returns
-------
ax : matplotlib axis
The axis with your equation.
"""
# clean equation string
eq = eq.strip('$').replace(' ', '')
# set up figure
f = plt.figure()
ax = plt.axes([0,0,1,1])
r = f.canvas.get_renderer()
# display equation
t = ax.text(0.5, 0.5, '${}$'.format(eq), fontsize=fontsize,
horizontalalignment='center',verticalalignment='center')
# resize figure to fit equation
bb = t.get_window_extent(renderer=r)
w,h = bb.width/f.dpi,np.ceil(bb.height/f.dpi)
f.set_size_inches((padding+w,padding+h))
# set axis limits so equation is centered
plt.xlim([0,1])
plt.ylim([0,1])
ax.grid(False)
ax.set_axis_off()
if outfile is not None:
plt.savefig(outfile, **kwargs)
return ax
生成 PNG。在我项目的机器人部分,我有
@client.command()
async def tex(ctx):
image = await plot_equation(eq)
await ctx.send(file=discord.File('path\to\file.png')
但我不确定如何将文件指向'path\to\file.png'。对此问题的任何帮助将不胜感激。