How to use the cairosvg.svg2png function in CairoSVG

To help you get started, we’ve selected a few CairoSVG examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chainer / chainer-chemistry / chainer_chemistry / saliency / visualizer / mol_visualizer.py View on Github external
drawer.DrawMolecule(
            mol, highlightAtoms=highlight_atoms,
            highlightAtomColors=atom_colors, highlightBonds=bondlist,
            highlightBondColors=bondcolorlist, legend=legend)
        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        if save_filepath:
            extention = save_filepath.split('.')[-1]
            if extention == 'svg':
                with open(save_filepath, 'w') as f:
                    f.write(svg)
            elif extention == 'png':
                # TODO(nakago): check it is possible without cairosvg or not
                try:
                    import cairosvg
                    cairosvg.svg2png(bytestring=svg, write_to=save_filepath)
                except ImportError as e:
                    self.logger.error(
                        'cairosvg is not installed! '
                        'Please install cairosvg to save by png format.\n'
                        'pip install cairosvg')
                    if raise_import_error:
                        raise e
            else:
                raise ValueError(
                    'Unsupported extention {} for save_filepath {}'
                    .format(extention, save_filepath))
        return svg
github byungsook / vectornet / pathnet / pathnet_data_sketch.py View on Github external
def preprocess(file_path, FLAGS):
    with open(file_path, 'r') as sf:
        svg = sf.read().format(w=FLAGS.image_width, h=FLAGS.image_height,
                               r=0, sx=1, sy=1, tx=0, ty=0)

    s_png = cairosvg.svg2png(bytestring=svg)
    s_img = Image.open(io.BytesIO(s_png))
    s = np.array(s_img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(s)
    s = s / max_intensity

    # # debug
    # plt.imshow(s, cmap=plt.cm.gray)
    # plt.show()

    # leave only one path
    svg_xml = et.fromstring(svg)
    # the first child of [0] is title
    # num_paths = len(svg_xml[0]._children) - 1
    num_paths = len(svg_xml[0]) - 1
    
    path_id_list = np.random.permutation(xrange(1,num_paths+1))
github byungsook / vectornet / data_kanji.py View on Github external
r = 0
    s = [1, 1]
    t = [0, 0]
    # if transform:
    #     r = rng.randint(-45, 45)
    #     # s_sign = rng.choice([1, -1], 1)[0]
    #     s_sign = 1
    #     s = 1.75 * rng.random_sample(2) + 0.25 # [0.25, 2)
    #     s[1] = s[1] * s_sign
    #     t = rng.randint(-10, 10, 2)
    #     if s_sign == -1:
    #         t[1] = t[1] - 109

    svg = svg.format(w=w, h=h, r=r, sx=s[0], sy=s[1], tx=t[0], ty=t[1])
    img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
    img = Image.open(io.BytesIO(img))
    s = np.array(img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(s)
    s = s / max_intensity

    # while True:
    pid = 0
    num_paths = 0
    while pid != -1:
        pid = svg.find('path id', pid + 1)
        num_paths = num_paths + 1
    num_paths = num_paths - 1 # uncount last one

    path_id = rng.randint(num_paths)
    svg_one = svg
    pid = len(svg_one)
github antooro / FlagsMashupBot / formatsvg.py View on Github external
def downloadPNGFlag(self, alpha3Code):
        #r = open(f"paises/{alpha3Code.lower()}.svg","r")
        r = requests.get(f"https://restcountries.eu/data/{alpha3Code.lower()}.svg")
        print(alpha3Code)
        cairosvg.svg2png(bytestring=r.text,write_to=f'{alpha3Code.lower()}.png')
github byungsook / vectornet / pathnet / pathnet_data_qdraw.py View on Github external
# # debug
    # plt.imshow(s, cmap=plt.cm.gray)
    # plt.show()

    num_paths = svg.count('polyline')
    while True:
        path_id = np.random.randint(1,num_paths+1)
        svg_xml = et.fromstring(svg)
        stroke = svg_xml[path_id]
        for c in reversed(xrange(1,num_paths+1)):
            if svg_xml[c] != stroke:
                svg_xml.remove(svg_xml[c])
        svg_one_stroke = et.tostring(svg_xml, method='xml')

        y_png = cairosvg.svg2png(bytestring=svg_one_stroke)
        y_img = Image.open(io.BytesIO(y_png))
        y = np.array(y_img)[:,:,3].astype(np.float) / max_intensity
        
        line_ids = np.nonzero(y)
        num_line_pixels = len(line_ids[0])

        if num_line_pixels > 0:
            break

    point_id = np.random.randint(num_line_pixels)
    ph, pw = line_ids[0][point_id], line_ids[1][point_id]

    y = np.reshape(y, [FLAGS.image_height, FLAGS.image_width, 1])
    x = np.zeros([FLAGS.image_height, FLAGS.image_width, 2])
    x[:,:,0] = s
    x[ph,pw,1] = 1.0
github byungsook / vectornet / ovnet / ovnet_data_sketch.py View on Github external
def preprocess(file_path, FLAGS):
    with open(file_path, 'r') as sf:
        svg = sf.read().format(w=FLAGS.image_width, h=FLAGS.image_height,
                               r=0, sx=1, sy=1, tx=0, ty=0)

    x_png = cairosvg.svg2png(bytestring=svg)
    x_img = Image.open(io.BytesIO(x_png))
    x = np.array(x_img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(x)
    x = x / max_intensity

    # # debug
    # plt.imshow(x, cmap=plt.cm.gray)
    # plt.show()


    y = np.zeros([FLAGS.image_height, FLAGS.image_width], dtype=np.bool)
    stroke_list = []
    svg_xml = et.fromstring(svg)
    num_paths = len(svg_xml[0])

    for i in xrange(1,num_paths):
github autophagy / scieldas / scieldas / image_creator.py View on Github external
def _create_png(text, height, width):
    svg = _create_svg(text, height, width)
    png = cairosvg.svg2png(
        bytestring=svg.tostring().encode(), parent_width=width, parent_height=height
    )
    return png
github byungsook / vectornet / graphcut_vec_chinese_new.py View on Github external
t = [0, 0]

        svg = svg.format(
            w=FLAGS.image_width, h=FLAGS.image_height,
            r=r, sx=s[0], sy=s[1], tx=t[0], ty=t[1])

        if FLAGS.chinese1:
            svg_xml = ET.fromstring(svg)
            num_paths = len(svg_xml[0]._children)

            for i in xrange(num_paths):
                svg_xml = ET.fromstring(svg)
                svg_xml[0]._children = [svg_xml[0]._children[i]]
                svg_one_stroke = ET.tostring(svg_xml, method='xml')

                y_png = cairosvg.svg2png(bytestring=svg_one_stroke)
                y_img = Image.open(io.BytesIO(y_png))
                y = (np.array(y_img)[:,:,3] > 0)

                # # debug
                # y_img = np.array(y_img)[:,:,3].astype(np.float) / 255.0
                # plt.imshow(y_img, cmap=plt.cm.gray)
                # plt.show()

                stroke_list.append(y)
        else:
            id = 0
            num_paths = 0
            while id != -1:
                id = svg.find('path id', id + 1)
                num_paths = num_paths + 1
            num_paths = num_paths - 1 # uncount last one
github byungsook / vectornet / ovnet / ovnet_data_line.py View on Github external
svg = SVG_START_TEMPLATE.format(
                width=FLAGS.image_width,
                height=FLAGS.image_height
            )
    y = np.zeros([FLAGS.image_height, FLAGS.image_width], dtype=np.int)
    stroke_list = []
    for i in xrange(FLAGS.num_paths):
        LINE1 = _create_a_path(FLAGS.path_type, i, FLAGS)
        svg_one_stroke = SVG_START_TEMPLATE.format(
                width=FLAGS.image_width,
                height=FLAGS.image_height
            ) + LINE1 + SVG_END_TEMPLATE
        svg += LINE1

        stroke_png = cairosvg.svg2png(bytestring=svg_one_stroke.encode('utf-8'))
        stroke_img = Image.open(io.BytesIO(stroke_png))
        stroke = (np.array(stroke_img)[:,:,3] > 0)

        # # debug
        # stroke_img = Image.open(io.BytesIO(stroke_png))
        # # stroke_img = np.array(stroke_img)[:,:,3].astype(np.float) / 255.0
        # plt.imshow(stroke_img)
        # plt.show()

        stroke_list.append(stroke)

    svg += SVG_END_TEMPLATE
    x_png = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
    x_img = Image.open(io.BytesIO(x_png))
    x = np.array(x_img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(x)