CircularArray
CircularArray

Reputation: 11

Saving an image with a specified width using preview()

I'm trying to save images of a formula, which I have written in LaTeX. Here's the formula:

triple_integral_formula = r"$$1)\int_{0}^{2\pi}\int_{0}^{\frac{\pi}{4}}\int_{0}^{3}\rho^2sin(\phi)d\rho d\phi d\theta$$"

I am using SymPy to save the images to later display on a PDF using reportlab. This is the code I have so far to do that:

preview(triple_integral_formula, viewer='file', filename='triple_integral.png', euler=False, dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600", "-bg", "Transparent"])

Here is the image output:

Image output

It might be hard to see because of the transparent background but all works well and it's saving the image properly. The only problem is that I want these images to be a certain width. From what I've read so far, the -D 600 section of the dvioptions list sets the "density", which I interpreted as the resolution. I tried to look online to find all of the different options that you can put inside the dvioptions list but couldn't find anything for setting width.

How can I accomplish this? Is a better way to display LaTeX formulas on a PDF (using reportlab or otherwise)?

Upvotes: 1

Views: 692

Answers (1)

wsdookadr
wsdookadr

Reputation: 2662

The problem with dvipng, it it only allows setting DPI, or dimensions in inches/centimeters but not width/height in pixels.

But you can work around this limitation by using Pillow which is an imaging library (the thumbnail method does preserve aspect ratio).

from sympy import *
triple_integral_formula = r"$$1)\int_{0}^{2\pi}\int_{0}^{\frac{\pi}{4}}\int_{0}^{3}\rho^2sin(\phi)d\rho d\phi d\theta$$"
preview(triple_integral_formula, viewer='file', filename='orig.png', euler=False, dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600", "-bg", "Transparent"])

from PIL import Image

for width in [400,300,200]:
    im = Image.open("orig.png")
    size = (width,200)
    im.thumbnail(size, Image.ANTIALIAS)
    out_dim = im.size
    out_name = "resized-"+str(out_dim[0])+"-"+str(out_dim[1])+".png"
    im.save(out_name,"PNG")
    im.close()

    from IPython.display import Image as i_image
    display(i_image(filename=out_name))

The last two lines are only present because I'm running this in Jupyter, but you can omit them and the images resized-<WIDTH>-<HEIGHT>.png will still be generated.

Output:

enter image description here

Upvotes: 1

Related Questions