Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 978f4da

Browse files
committed
Better color options and added scale
1 parent f91fc4e commit 978f4da

2 files changed

Lines changed: 49 additions & 8 deletions

File tree

IPython/lib/latextools.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import shutil
1111
import subprocess
1212
from base64 import encodebytes
13+
from textwrap import wrap as splitstring
1314

1415
from IPython.utils.process import find_cmd, FindCmdError
1516
from traitlets.config import get_config
@@ -55,7 +56,8 @@ def _config_default(self):
5556
).tag(config=True)
5657

5758

58-
def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black'):
59+
def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black',
60+
scale=1.0):
5961
"""Render a LaTeX string to PNG.
6062
6163
Parameters
@@ -69,7 +71,10 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black'):
6971
wrap : bool
7072
If true, Automatically wrap `s` as a LaTeX equation.
7173
color : string
72-
Foreground color name among dvipsnames.
74+
Foreground color name among dvipsnames, e.g. 'Maroon' or on hex RGB
75+
format, e.g. '#AA20FA'.
76+
scale : float
77+
Scale factor for the resulting PNG.
7378
7479
None is returned when the backend cannot be used.
7580
@@ -84,15 +89,25 @@ def latex_to_png(s, encode=False, backend=None, wrap=False, color='Black'):
8489
f = latex_to_png_mpl
8590
elif backend == 'dvipng':
8691
f = latex_to_png_dvipng
92+
if color.startswith('#'):
93+
# Convert hex RGB color to LaTeX RGB color.
94+
if len(color) == 7:
95+
try:
96+
color = "RGB {}".format(" ".join([str(int(x, 16)) for x in
97+
splitstring(color[1:], 2)]))
98+
except ValueError:
99+
raise ValueError('Invalid color specification {}.'.format(color))
100+
else:
101+
raise ValueError('Invalid color specification {}.'.format(color))
87102
else:
88103
raise ValueError('No such backend {0}'.format(backend))
89-
bin_data = f(s, wrap, color)
104+
bin_data = f(s, wrap, color, scale)
90105
if encode and bin_data:
91106
bin_data = encodebytes(bin_data)
92107
return bin_data
93108

94109

95-
def latex_to_png_mpl(s, wrap, color='Black'):
110+
def latex_to_png_mpl(s, wrap, color='Black', scale=1.0):
96111
try:
97112
from matplotlib import mathtext
98113
from pyparsing import ParseFatalException
@@ -107,13 +122,14 @@ def latex_to_png_mpl(s, wrap, color='Black'):
107122
try:
108123
mt = mathtext.MathTextParser('bitmap')
109124
f = BytesIO()
110-
mt.to_png(f, s, fontsize=12, color=color)
125+
dpi = 120*scale
126+
mt.to_png(f, s, fontsize=12, dpi=dpi, color=color)
111127
return f.getvalue()
112128
except (ValueError, RuntimeError, ParseFatalException):
113129
return None
114130

115131

116-
def latex_to_png_dvipng(s, wrap, color='Black'):
132+
def latex_to_png_dvipng(s, wrap, color='Black', scale=1.0):
117133
try:
118134
find_cmd('latex')
119135
find_cmd('dvipng')
@@ -133,8 +149,9 @@ def latex_to_png_dvipng(s, wrap, color='Black'):
133149
["latex", "-halt-on-error", "-interaction", "batchmode", tmpfile],
134150
cwd=workdir, stdout=devnull, stderr=devnull)
135151

152+
resolution = round(150*scale)
136153
subprocess.check_call(
137-
["dvipng", "-T", "tight", "-x", "1500", "-z", "9",
154+
["dvipng", "-T", "tight", "-D", str(resolution), "-z", "9",
138155
"-bg", "transparent", "-o", outfile, dvifile, "-fg", color],
139156
cwd=workdir, stdout=devnull, stderr=devnull)
140157

IPython/lib/tests/test_latextools.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,24 +134,48 @@ def mock_kpsewhich(filename):
134134
\end{document}''')
135135

136136

137+
@skipif_not_matplotlib
138+
@onlyif_cmds_exist('latex', 'dvipng')
137139
def test_latex_to_png_color():
138140
"""
139141
Test color settings for latex_to_png.
140142
"""
141143
latex_string = "$x^2$"
142144
default_value = latextools.latex_to_png(latex_string, wrap=False)
145+
default_hexblack = latextools.latex_to_png(latex_string, wrap=False,
146+
color='#000000')
143147
dvipng_default = latextools.latex_to_png_dvipng(latex_string, False)
144148
dvipng_black = latextools.latex_to_png_dvipng(latex_string, False, 'Black')
145149
nt.assert_equal(dvipng_default, dvipng_black)
146150
mpl_default = latextools.latex_to_png_mpl(latex_string, False)
147151
mpl_black = latextools.latex_to_png_mpl(latex_string, False, 'Black')
148152
nt.assert_equal(mpl_default, mpl_black)
149153
nt.assert_in(default_value, [dvipng_black, mpl_black])
154+
nt.assert_in(default_hexblack, [dvipng_black, mpl_black])
150155

151156
# Test that dvips name colors can be used without error
152-
dvipng_maroon = latextools.latex_to_png_dvipng(latex_string, False, 'Maroon')
157+
dvipng_maroon = latextools.latex_to_png_dvipng(latex_string, False,
158+
'Maroon')
153159
# And that it doesn't return the black one
154160
nt.assert_not_equal(dvipng_black, dvipng_maroon)
155161

156162
mpl_maroon = latextools.latex_to_png_mpl(latex_string, False, 'Maroon')
157163
nt.assert_not_equal(mpl_black, mpl_maroon)
164+
mpl_white = latextools.latex_to_png_mpl(latex_string, False, 'White')
165+
mpl_hexwhite = latextools.latex_to_png_mpl(latex_string, False, '#FFFFFF')
166+
nt.assert_equal(mpl_white, mpl_hexwhite)
167+
168+
mpl_white_scale = latextools.latex_to_png_mpl(latex_string, False,
169+
'White', 1.2)
170+
nt.assert_not_equal(mpl_white, mpl_white_scale)
171+
172+
173+
def test_latex_to_png_invalid_hex_colors():
174+
"""
175+
Test that invalid hex colors provided to dvipng gives an exception.
176+
"""
177+
latex_string = "$x^2$"
178+
nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
179+
backend='dvipng', color="#f00bar"))
180+
nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
181+
backend='dvipng', color="#f00"))

0 commit comments

Comments
 (0)