[EDIT : The image should stay within Mathematica so I can not use Export["file.svg", expression]
as Import
does not support svg files]
Consider the expression $1+x^2$. One can convert this expression into an image using
ImportByteArray@ExportByteArray[1 + x^2, "PNG"]
or
ImportString@ExportString[1 + x^2, "PNG"]
However, the image quality is bad (pixeled). Changing "PNG" to "EPS" leads to a full black image (or white depending on the stylesheet) and changing "PNG" to "PDF" also leads to an image with bad quality (pixeled).
My solution was this rather complicated code that gives a nice image
Style[Text[1 + x^2], FontSize -> 100] // Graphics // Image //
ExportByteArray[#, "PDF"] & // ImportByteArray // First //
Image[#, ImageSize -> 50] &
(ImageCrop
in the above code could also be useful)
But that code looks like it depends a lot on the size of the expression. For example changing 1+x^2 with Nest[Integrate[#, x] &, x*Log[x]/(x^2 + 4), 2]
shows the wrong output image when compared with the actual output.
(Pane
could be useful here but it required some fiddling around)
I suppose that a solution for this is to clip the image around the expression. How could one do that ?
Are there other ways to obtain nice images from an expression ?
The two test expressions:
1 + x^2
Nest[Integrate[#, x] &, x*Log[x]/(x^2 + 4), 2]
EDIT
Using
ImportByteArray[
x^2 + 1 // ExportByteArray[#, "PDF"] &, {"PDF",
"PageGraphics"}] // First
I got a nice image but it is a Graphics
object. I did not find a way to turn that into a crisp image with the same size. A solution that requires adjusting image resolution and image size would be too tedious for me.
EDIT2:
There is a resource function SVGImport by a Wolfram research member that allows importing svg files using ExternalEvaluate
and Python (so it might not work if Python is not configured to work with Mathematica). The resulting object is a Graphics
object. The method seems to use PDF as an intermediate so I do not know if there is a benefit from exporting and importing as SVG rather than PDF.
Using Magnify
with either the PDF or SVG method gave some nice results.
ExportByteArray
rather thanExport
. I wish I could use SVG withImport
orImportByteArray
but it seems Mathematica does not support importing this format. $\endgroup$ExternalEvaluate
to evaluate toPython
so it might not work if Pythonis not set up to work like that. $\endgroup$