1

How do you convert an SVG image to PNG, but proportionally scale it up, using Python?

I have an SVG "sprite" that I'm trying to load at different resolutions, small/medium/large/etc.

I tried some of the answers suggested in this question like:

svg = Parser.parse_file(filename)
rast = Rasterizer()
buff = rast.rasterize(svg, w, h)
image = pygame.image.frombuffer(buff, (w, h), 'ARGB')

However, none of them work as expected. Specifically, the width and height parameters have no effect on the size of the rasterized pixels, only the overall size of the PNG. Whether I use w=10, h=10 or w=10000, h=10000, the image contains the same rasterized image (whose dimensions I suspect are being pulled from the root width/height/viewbox parameters in my svg file), but the larger dimensions just have a ton more padding.

I don't have the larger image to just be the smaller image with a lot of extra empty space. I want the larger image to be a scaled up version of the smaller image. How do I do this?

Cerin
  • 60,957
  • 96
  • 316
  • 522

1 Answers1

1

Here my take on this problem:

    from PIL import Image # to convert into any image format
    from cairosvg import svg2png

    img_width, img_height = 1024,768
    with open("example.svg","rb") as f:
         svg_data = f.read() ##  binary SVG data from any source
    svg_png_image = svg2png(bytestring=svg_data, output_width=img_width, output_height=img_height) # convert to PNG with img_width/img_height
    img1 = Image.open(BytesIO(svg_png_image)) # pass to PIL
    img1.save(buf, format='JPEG', compress_level=1) # or PNG or any other 
    image_data_buf = buf.getvalue()

In my case, I set img_width, img_height according to my image that I will paste it into. You may find many interesting examples of use here.

Also, there is the following way to use svg2png:

cairo.svg2png(url="/path/to/input.svg", write_to="/tmp/output.png")

I didn't find a detailed description of function svg2png, but you derive the purposes from parameters naming. Hope someone will add it to this article.