如何将乳胶数学方程作为Python中的图像保存?

发布于 2025-01-22 09:30:11 字数 646 浏览 4 评论 0原文

我想将我的乳胶方程保存为.png或python中的图像。

import sympy                                                               

x = sympy.symbols('x')                                                          
y = 1 + sympy.sin(sympy.sqrt(x**2 + 20))                                         
lat = sympy.latex(y)

from PIL import Image, ImageDraw


W, H = (300,200)


im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
w, h = draw.textsize(lat)
draw.text(((W-w)/2,(H-h)/2), r"$%s$" % lat, fill="black")
im.save(r'hello.png','PNG')

我获得的输出没有显示乳胶方程 “这是输出IM获取”

I want to save my latex equations as .png or image in python.

import sympy                                                               

x = sympy.symbols('x')                                                          
y = 1 + sympy.sin(sympy.sqrt(x**2 + 20))                                         
lat = sympy.latex(y)

from PIL import Image, ImageDraw


W, H = (300,200)


im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
w, h = draw.textsize(lat)
draw.text(((W-w)/2,(H-h)/2), r"$%s
quot; % lat, fill="black")
im.save(r'hello.png','PNG')

The output i am getting is not showing the latex equation
this is the output im getting

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞳孔里扚悲伤 2025-01-29 09:30:13

我建议使用matplotlib,并且做类似的事情:

def latex_to_image(math_expr: str, file_name: str, location: str, file_format: str = 'png',
               picture_dims: Union[str,Tuple[float,float]] = 'A4',
               resolution: Union[float, int] = 300, transparent: bool = True) -> None:
"""
Converts a LaTeX math expression to an image in the specified file format and saves it with the specified file name.

Args:
    math_expr (str): The LaTeX math expression to be converted to an image.
    file_name (str): The name of the file to be saved.
    file_format (str, optional): The format of the output file. Defaults to 'png'.
    picture_dims (Union[str,Tuple[float,float]], optional): The dimensions of the output picture. Can be either a
                                                           string specifying one of the standard dimensions (Letter,
                                                           Legal, A4, A5) or a tuple of the form (width, height).
                                                           Defaults to 'A4'.
    resolution (Union[float, int], optional): The resolution of the output image in DPI (dots per inch). Defaults to 300.
    transparent (bool, optional): Whether to save the image with a transparent background. Defaults to True.

Raises:
    ValueError: If picture_dims is not one of the standard dimensions (Letter, Legal, A4, A5).
"""

# Standard square dimensions of output picture
std_dims = {"Letter":(8.5,14.0), "Legal":(8.5,14.0),
            "A4":(8.3,11.7), "A5":(5.8, 8.3)}

if picture_dims in list(std_dims.keys()):
    DIMS = std_dims[picture_dims]
else:
    raise ValueError(f"{picture_dims} not known - should be in: {list(std_dims.keys())}.")

# Create the download directory if it doesn't exist
if not os.path.exists(location):
    # Notify the user that the download directory was created
    print(f"N.B.: Path '{location}' didn't already exist, so it was created... ")
    os.makedirs(location)

# Set the LaTeX font
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'

# Add $ symbols to format the string as an inline math expression
inline_expr = to_inline_expr(math_expr=math_expr)

# Create a plot with the expression
fig, ax = plt.subplots(figsize=DIMS)
ax.text(0.5, 0.5, inline_expr, size=20, ha='center')

# Remove the plot axes
ax.set_axis_off()

# Save the plot as a PNG with a transparent background
plt.savefig(fname=location+file_name+"."+file_format, format=file_format, transparent=transparent, bbox_inches='tight', pad_inches=0.0, dpi=resolution)
plt.close(fig)

I recommend using Matplotlib, and the doing something similar to:

def latex_to_image(math_expr: str, file_name: str, location: str, file_format: str = 'png',
               picture_dims: Union[str,Tuple[float,float]] = 'A4',
               resolution: Union[float, int] = 300, transparent: bool = True) -> None:
"""
Converts a LaTeX math expression to an image in the specified file format and saves it with the specified file name.

Args:
    math_expr (str): The LaTeX math expression to be converted to an image.
    file_name (str): The name of the file to be saved.
    file_format (str, optional): The format of the output file. Defaults to 'png'.
    picture_dims (Union[str,Tuple[float,float]], optional): The dimensions of the output picture. Can be either a
                                                           string specifying one of the standard dimensions (Letter,
                                                           Legal, A4, A5) or a tuple of the form (width, height).
                                                           Defaults to 'A4'.
    resolution (Union[float, int], optional): The resolution of the output image in DPI (dots per inch). Defaults to 300.
    transparent (bool, optional): Whether to save the image with a transparent background. Defaults to True.

Raises:
    ValueError: If picture_dims is not one of the standard dimensions (Letter, Legal, A4, A5).
"""

# Standard square dimensions of output picture
std_dims = {"Letter":(8.5,14.0), "Legal":(8.5,14.0),
            "A4":(8.3,11.7), "A5":(5.8, 8.3)}

if picture_dims in list(std_dims.keys()):
    DIMS = std_dims[picture_dims]
else:
    raise ValueError(f"{picture_dims} not known - should be in: {list(std_dims.keys())}.")

# Create the download directory if it doesn't exist
if not os.path.exists(location):
    # Notify the user that the download directory was created
    print(f"N.B.: Path '{location}' didn't already exist, so it was created... ")
    os.makedirs(location)

# Set the LaTeX font
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'

# Add $ symbols to format the string as an inline math expression
inline_expr = to_inline_expr(math_expr=math_expr)

# Create a plot with the expression
fig, ax = plt.subplots(figsize=DIMS)
ax.text(0.5, 0.5, inline_expr, size=20, ha='center')

# Remove the plot axes
ax.set_axis_off()

# Save the plot as a PNG with a transparent background
plt.savefig(fname=location+file_name+"."+file_format, format=file_format, transparent=transparent, bbox_inches='tight', pad_inches=0.0, dpi=resolution)
plt.close(fig)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文