Python cairosvg.svg2png() Examples

The following are 13 code examples of cairosvg.svg2png(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cairosvg , or try the search function .
Example #1
Source File: generate_integration_bots_avatars.py    From zulip with Apache License 2.0 7 votes vote down vote up
def create_integration_bot_avatar(logo_path: str, bot_avatar_path: str) -> None:
    if logo_path.endswith('.svg'):
        avatar = cairosvg.svg2png(
            url=logo_path, output_width=DEFAULT_AVATAR_SIZE, output_height=DEFAULT_AVATAR_SIZE)
    else:
        with open(logo_path, 'rb') as f:
            image = f.read()
        square_image = create_square_image(image)
        avatar = resize_avatar(square_image)

    os.makedirs(os.path.dirname(bot_avatar_path), exist_ok=True)
    with open(bot_avatar_path, 'wb') as f:
        f.write(avatar) 
Example #2
Source File: image.py    From py_ball with MIT License 6 votes vote down vote up
def __init__(self, league='WNBA',
                 team_id='1611661319',
                 season_year='2017-18'):

        # Controlling the parameters depending on the endpoint
        if league == 'WNBA':
            team_str = ID_TO_TEAM_WNBA[team_id]
            response = requests.get(BASE_WNBA_LOGO_URL.format(team=team_str))
        elif league == 'NBA':
            team_str = ID_TO_TEAM_NBA[team_id]
            response = requests.get(BASE_NBA_LOGO_URL.format(team=team_str,
                                                             year=season_year))
        elif league == 'G':
            team_str = ID_TO_TEAM_G_LEAGUE[team_id]
            response = requests.get(BASE_G_LEAGUE_LOGO_URL.format(team=team_str))

        new_bites = svg2png(bytestring=response.content,
                            write_to=None)
        im = Image.open(BytesIO(new_bites))
        self.image = im 
Example #3
Source File: updater.py    From dnfdragora with GNU General Public License v3.0 5 votes vote down vote up
def __svg_to_Image(self, svg_string):
      '''
        gets svg content and returns a PIL.Image object
      '''
      import cairosvg
      import io
      in_mem_file = io.BytesIO()
      cairosvg.svg2png(bytestring=svg_string, write_to=in_mem_file)
      return Image.open(io.BytesIO(in_mem_file.getvalue())) 
Example #4
Source File: raster.py    From drawSvg with MIT License 5 votes vote down vote up
def fromSvg(svgData):
        pngData = cairosvg.svg2png(bytestring=svgData)
        return Raster(pngData) 
Example #5
Source File: raster.py    From drawSvg with MIT License 5 votes vote down vote up
def fromSvgToFile(svgData, outFile):
        cairosvg.svg2png(bytestring=svgData, write_to=outFile)
        return Raster(None, pngFile=outFile) 
Example #6
Source File: downloader.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def generate_cover(app):
    logger.info('Generating cover image...')
    if svg2png is None:
        return
    # end if
    try:
        svg_file = os.path.join(app.output_path, 'cover.svg')
        svg = random_cover(
            title=app.crawler.novel_title,
            author=app.crawler.novel_author,
        )

        with open(svg_file, 'w', encoding='utf-8') as f:
            f.write(svg)
            logger.debug('Saved a random cover.svg')
        # end with

        png_file = os.path.join(app.output_path, 'cover.png')
        svg2png(bytestring=svg.encode('utf-8'), write_to=png_file)
        logger.debug('Converted cover.svg to cover.png')

        return png_file
    except Exception:
        logger.exception('Failed to generate cover image: %s', app.output_path)
        return None
    # end try
# end def 
Example #7
Source File: server.py    From web-boardimage with GNU Affero General Public License v3.0 5 votes vote down vote up
def render_png(self, request):
        svg_data = self.make_svg(request)
        png_data = cairosvg.svg2png(bytestring=svg_data)
        return aiohttp.web.Response(body=png_data, content_type="image/png") 
Example #8
Source File: make.py    From atom-icons with MIT License 5 votes vote down vote up
def make_linux():
    if not os.path.exists('linux'):
        os.makedirs('linux')
    for file in os.listdir('svg'):
        if file.endswith(".svg"):
            svg2png(url="svg/"+file, write_to="linux/" + file.split('.')[0] + ".png", parent_width=256, parent_height=256) 
Example #9
Source File: make.py    From atom-icons with MIT License 5 votes vote down vote up
def get_size_name(size):
    if size[1] == 144:
        return str(size[0]//2) + 'x' + str(size[0]//2) + '@2x'
    return str(size[0]) + 'x' + str(size[0])

# def prep_macOS():
#     if not os.path.exists('macOS'):
#         os.makedirs('macOS')
#     for file in os.listdir('svg'):
#         if file.endswith(".svg"):
#             if not os.path.exists('macOS/'+file.split('.')[0] + '.iconset/'):
#                 os.makedirs('macOS/'+file.split('.')[0] + '.iconset/')
#             for size in ICNS_SIZES:
#                 svg2png(url="svg/"+file, write_to="macOS/"+file.split('.')[0] + '.iconset/icon_' + get_size_name(size) + ".png", parent_width=size[0], parent_height=size[0], dpi=size[1]) 
Example #10
Source File: Fun.py    From NotSoBot with MIT License 5 votes vote down vote up
def png_svg(self, path, size):
		with open(path, 'rb') as f:
			path = f.read()
		s = bytes(str(size), encoding="utf-8")
		b = path.replace(b"<svg ", b"<svg width=\"" + s + b"px\" height=\"" + s + b"px\" ")
		path = BytesIO(cairosvg.svg2png(b))
		return path 
Example #11
Source File: render.py    From readme2tex with MIT License 5 votes vote down vote up
def svg2png(svg):
    # assume that 'cairosvg' exists
    import cairosvg
    cairosvg.svg2png(url=svg, write_to=svg[:-4] + '.png', dpi=250)
    return svg[:-4] + '.png' 
Example #12
Source File: export.py    From builder with GNU Affero General Public License v3.0 4 votes vote down vote up
def dashExport(request, code):
  """
  Handler function to export dashboard to SVG, PDF, or PNG.

  Args:
    request: Django request object.
    exportType: A string corresponding to the format for export.
    code: A code to identify the serialized data stored in the session field of
      the Django request.

  Returns:
    A file that corresponds to the dashboard encoded by `serial`, in the format
    requested.

  Raises:
    ValueError: Thrown when an invalid export type is passed in.
  """
  if not settings.EXPORT_SERVICE_PORT:
    raise ValueError('Received an export request, but exporting is not enabled')

  data       = request.session[code]
  serial     = data['serial']
  exportType = data['exportType']

  svg = _getSvg(request, serial)
  res, contentType = None, None

  if   exportType == 'svg':
    res = svg
    contentType = "image/svg+xml"
  else:
    import cairosvg
    # pylint: disable = E1101
    # Pylint does not recognize svg2pdf/svg2png method in cairosvg
    if exportType == 'pdf':
      res = cairosvg.svg2pdf(svg)
      contentType = "application/pdf"
    elif exportType == 'png':
      res = cairosvg.svg2png(svg)
      contentType = "image/png"
    else:
      raise ValueError("views.export.dashExport: Invalid export format, %s" % exportType)

  response = HttpResponse(res, content_type=contentType)
  response['Content-Disposition'] = "attachment;filename=dashboard." + exportType
  return response

#### Helper methods for rendering 
Example #13
Source File: export.py    From builder with GNU Affero General Public License v3.0 4 votes vote down vote up
def dashExport(request, code):
  """
  Handler function to export dashboard to SVG, PDF, or PNG.

  Args:
    request: Django request object.
    exportType: A string corresponding to the format for export.
    code: A code to identify the serialized data stored in the session field of
      the Django request.

  Returns:
    A file that corresponds to the dashboard encoded by `serial`, in the format
    requested.

  Raises:
    ValueError: Thrown when an invalid export type is passed in.
  """
  if not settings.EXPORT_SERVICE_PORT:
    raise ValueError('Received an export request, but exporting is not enabled')

  data       = request.session[code]
  serial     = data['serial']
  exportType = data['exportType']

  svg = _getSvg(request, serial)
  res, contentType = None, None

  if   exportType == 'svg':
    res = svg
    contentType = "image/svg+xml"
  else:
    import cairosvg
    # pylint: disable = E1101
    # Pylint does not recognize svg2pdf/svg2png method in cairosvg
    if exportType == 'pdf':
      res = cairosvg.svg2pdf(svg)
      contentType = "application/pdf"
    elif exportType == 'png':
      res = cairosvg.svg2png(svg)
      contentType = "image/png"
    else:
      raise ValueError("views.export.dashExport: Invalid export format, %s" % exportType)

  response = HttpResponse(res, content_type=contentType)
  response['Content-Disposition'] = "attachment;filename=dashboard." + exportType
  return response

#### Helper methods for rendering