예제 #1
0
 def block_math(name, text):
     text = '$%s$' % text.strip()
     f = BytesIO()
     mathtext.math_to_image(text, f, dpi=120, format='pdf')
     img = PdfImage(f)
     img.hAlign = 'CENTER'
     return [Spacer(1, 4), img, Spacer(1, 4)]
예제 #2
0
    def createWidgets(self, text):

        #Creating buffer for storing image in memory
        buffer = BytesIO()
        #Writing png image with our rendered greek alpha to buffer
        math_to_image(text, buffer, dpi=1000, format='png')

        #Remoting bufeer to 0, so that we can read from it
        buffer.seek(0)

        # Creating Pillow image object from it
        pimage= Image.open(buffer)

        #Creating PhotoImage object from Pillow image object
        image = ImageTk.PhotoImage(pimage)

        #Creating label with our image
        label = tk.Label(self,image=image)

        #Storing reference to our image object so it's not garbage collected,
        # as TkInter doesn't store references by itself
        label.img = image

        e = 'image'
        return label, e
예제 #3
0
def parse_math(message):
    equations = regexp_latex.findall(message)

    replacements = list()
    for eq in equations:
        output = StringIO()
        try:
            mathtext.math_to_image(eq,
                                   output,
                                   dpi = 72,
                                   prop = font_properties,
                                   format = 'svg')
            svg_equation = ''.join(output.getvalue().split('\n')[4:])
            replacements.append(svg_equation)

        except ValueError:
            replacements.append('<i>Error in equation</i>')

        output.close()

    newmessage = regexp_latex.sub('{}', message)
    
    try:
        newmessage = newmessage.format(*replacements)
    except:
        newmessage = 'Could not understand your message'
        
    return newmessage
예제 #4
0
    def createWidgets(self):

        # Creating buffer for storing image in memory
        buffer = BytesIO()

        # Writing png image with our rendered greek alpha to buffer
        math_to_image('$\\int_C \\vec{F}\\cdot \\vec{dr}$',
                      buffer,
                      dpi=1000,
                      format='png')

        # Remoting bufeer to 0, so that we can read from it
        buffer.seek(0)

        # Creating Pillow image object from it
        pimage = Image.open(buffer)

        # Creating PhotoImage object from Pillow image object
        image = ImageTk.PhotoImage(pimage)

        # Creating label with our image
        self.label = tk.Label(self, image=image)

        # Storing reference to our image object so it's not garbage collected,
        # as TkInter doesn't store references by itself
        self.label.img = image

        self.label.pack(side="bottom")
        self.QUIT = tk.Button(self,
                              text="QUIT",
                              fg="red",
                              command=root.destroy)
        self.QUIT.pack(side="top")
예제 #5
0
파일: fm.py 프로젝트: xufive/wxgl
    def text2alpha(self, text, size, family=None, weight='normal'):
        """文本转透明通道
        
        text        - 文本字符串
        size        - 文字大小,整型
        family      - (系统支持的)字体
        weight      - 字体的浓淡:'normal'-正常(默认),'light'-轻,'bold'-重
        """

        p = re.compile(r'\$.+\$')
        if p.search(text):
            if family not in self.fonts:
                family = self.default_font

            bfo = BytesIO()
            prop = mfm.FontProperties(family=family, size=size, weight=weight)
            mathtext.math_to_image(text, bfo, prop=prop, dpi=72)

            im = Image.open(bfo)
            r, g, b, a = im.split()
            r, g, b = 255 - np.array(r), 255 - np.array(g), 255 - np.array(b)
            pixels = np.uint8(r / 3 + g / 3 + b / 3)
        else:
            font_file = self.get_font_file(family=family, weight=weight)
            pixels = self.get_text_pixels(text, size, font_file)

        return pixels
예제 #6
0
파일: main.py 프로젝트: VJsong02/jod-2.0
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == 'lån?':
        await message.channel.send(embed=gen_embed())

    if message.content.startswith("$wa"):
        query = message.content[3:].strip()
        url = "http://api.wolframalpha.com/v1/simple?appid={}&units=metric&i={}"\
            .format(json.load(open('config.json',))['wolfram'], urllib.parse.quote(query))
        await message.channel.send(file=discord.File(
            io.BytesIO(requests.get(url).content), "result.png"))

    if message.content.startswith("$math"):
        buffer = io.BytesIO()
        properties = font_manager.FontProperties(size=36)

        mathtext.math_to_image("${}$".format(
            message.content[5:].strip().replace("\n", "").replace("`", "")),
                               buffer,
                               format="png",
                               prop=properties,
                               dpi=96)
        buffer.seek(0)
        im = Image.open(buffer)
        image_data = np.asarray(im)
        image_data_bw = image_data.max(axis=2)
        non_empty_columns = np.where(image_data_bw.max(axis=0) > 0)[0]
        non_empty_rows = np.where(image_data_bw.max(axis=1) > 0)[0]
        cropBox = (min(non_empty_rows), max(non_empty_rows),
                   min(non_empty_columns), max(non_empty_columns))
        image_data_new = image_data[cropBox[0]:cropBox[1] + 1,
                                    cropBox[2]:cropBox[3] + 1, :]
        wx = 1
        wc = 10
        hx = 1
        hc = 10
        im = Image.fromarray(image_data_new)
        new_size = (int(im.size[0] * wx + wc * 2),\
            int(im.size[1] * hx + hc * 2))
        img = Image.new("RGB", new_size, (255, 255, 255))
        img.paste(im, ((new_size[0] - im.size[0]) // 2,
                       (new_size[1] - im.size[1]) // 2))

        newbuffer = io.BytesIO()
        img.save(newbuffer, format="PNG")
        newbuffer.seek(0)

        await message.channel.send(file=discord.File(newbuffer, "maths.png"))
예제 #7
0
def latex2png(latex, filename, fontset='cm', fontsize=10, dpi=100):
    with mpl.rc_context({'mathtext.fontset': fontset, 'font.size': fontsize}):
        try:
            depth = mathtext.math_to_image(f"${latex}$",
                                           filename,
                                           dpi=dpi,
                                           format="png")
        except Exception:
            _api.warn_external(f"Could not render math expression {latex}")
            depth = 0
    return depth
예제 #8
0
def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex
    with mpl.rc_context({'mathtext.fontset': fontset}):
        try:
            depth = mathtext.math_to_image(latex,
                                           filename,
                                           dpi=100,
                                           format="png")
        except Exception:
            _api.warn_external(f"Could not render math expression {latex}")
            depth = 0
    return depth
예제 #9
0
파일: fm.py 프로젝트: xufive/wxgl
    def text2img(self, text, size, color, family=None, weight='normal'):
        """文本转图像,返回图像数据和size元组
        
        text        - 文本字符串
        size        - 文字大小,整型
        color       - 文本颜色,numpy数组
        family      - (系统支持的)字体
        weight      - 字体的浓淡:'normal'-正常(默认),'light'-轻,'bold'-重
        """

        p = re.compile(r'\$.+\$')
        if p.search(text):
            if family not in self.fonts:
                family = self.default_font

            bfo = BytesIO()
            prop = mfm.FontProperties(family=family, size=size, weight=weight)
            mathtext.math_to_image(text, bfo, prop=prop, dpi=72)

            im = Image.open(bfo)
            r, g, b, a = im.split()
            r, g, b = 255 - np.array(r), 255 - np.array(g), 255 - np.array(b)
            a = r / 3 + g / 3 + b / 3

            r, g, b = r * color[0], g * color[1], b * color[2]
            im = np.dstack((r, g, b, a)).astype(np.uint8)
        else:
            font_file = self.get_font_file(family=family, weight=weight)
            pixels = self.get_text_pixels(text, size, font_file)
            rows, cols = pixels.shape

            r = np.ones(pixels.shape) * color[0] * 255
            g = np.ones(pixels.shape) * color[1] * 255
            b = np.ones(pixels.shape) * color[2] * 255
            im = np.dstack((r, g, b, pixels)).astype(np.uint8)

        return im
예제 #10
0
def laTeX(text, color, size):
    # Set text color.
    matplotlib.rcParams['text.color'] = color
    matplotlib.rcParams['font.size'] = size

    # Turn math to image with black background.
    buffer = BytesIO()
    math_to_image(text, buffer, dpi=75, format='svg')
    buffer.seek(0)
    pimage = Image.open(buffer)

    # Remove black background to make transparent.
    data = pimage.getdata()
    newData = []
    for item in data:
        T = 0
        if item[0] <= T and item[1] <= T and item[2] <= T:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
    pimage.putdata(newData)

    # Return final PhotoImage object to display.
    return ImageTk.PhotoImage(pimage)
예제 #11
0
def test_math_to_image(tmpdir):
    mathtext.math_to_image('$x^2$', str(tmpdir.join('example.png')))
    mathtext.math_to_image('$x^2$', io.BytesIO())
예제 #12
0
# coding: utf-8

# https://forum.omz-software.com/topic/2431/possible-to-implement-latex-in-scene-module

import matplotlib.mathtext as mt
s = r'$\frac{A}{B} = C$'
mt.math_to_image(s, 'test.png')
matplotlib.rcParams['text.color'] = _from_rgb(apple_colors['lightindigo'])
matplotlib.rcParams['savefig.facecolor'] = 'black'
matplotlib.rcParams['savefig.bbox'] = 'tight'

fig, ax = plt.subplots(1, 1)
fig.patch.set_alpha(0.5)

from PIL import ImageTk, Image
# Creating buffer for storing image in memory
buffer = BytesIO()

# Writing png image with our rendered greek alpha to buffer
# math_to_image('$\\int_C \\vec{F}\\cdot \\vec{dr}$', buffer, dpi=600, format='png')
# math_to_image('$\\int f(x)\\ dx$', buffer, dpi=600, format='png')
math_to_image('$\\int_C \\vec{F}\\cdot \\vec{dr}$',
              buffer,
              dpi=400,
              format='png')

# Remoting bufeer to 0, so that we can read from it
buffer.seek(0)

# Creating Pillow image object from it
pimage = Image.open(buffer)

# Remove all black ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
img = pimage
datas = img.getdata()

newData = []
for item in datas:
    if item[0] == 0 and item[1] == 0 and item[2] == 0:
예제 #14
0
parser.add_argument('--family', default='serif')
parser.add_argument('--mathfamily', default='dejavuserif')
parser.add_argument('--style', default='italic')
parser.add_argument('--size', default=16, type=int)
parser.add_argument('--base64', action='store_true')
parser.add_argument('--markdown', action='store_true')
args = parser.parse_args()

font = FontProperties(family=args.family,
                      math_fontfamily=args.mathfamily,
                      style=args.style,
                      size=args.size)

buffer = BytesIO()
mathtext.math_to_image(r'{}'.format(args.input),
                       buffer,
                       prop=font,
                       format='svg')

buffer.seek(0)

if args.base64:
    encoded = 'data:image/svg+xml;base64,{}'.format(
        base64.b64encode(buffer.read()).decode('utf-8'))

    if args.markdown:
        print('base64 and markdown no support', file=sys.stderr)
    else:
        print(encoded, end='')

else: