【问题标题】:How to rasterize SVG in Python at arbitrary size如何在 Python 中以任意大小栅格化 SVG
【发布时间】:2020-09-02 19:56:20
【问题描述】:

如何使用 Python 将 SVG 图像转换为 PNG,并按比例放大?

我有一个 SVG “精灵”,我正尝试以不同的分辨率(小/中/大/等)加载。

我尝试了this question 中建议的一些答案,例如:

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

但是,它们都没有按预期工作。具体来说,宽度和高度参数对光栅化像素的大小没有影响,只会影响 PNG 的整体大小。无论我使用 w=10、h=10 还是 w=10000、h=10000,图像都包含相同的光栅化图像(我怀疑其尺寸是从我的 svg 文件中的根宽度/高度/视图框参数中提取的),但是更大的尺寸只是有更多的填充。

我没有更大的图像,只是具有大量额外空白空间的较小图像。我希望较大的图像是较小图像的放大版本。我该怎么做?

【问题讨论】:

    标签: python svg


    【解决方案1】:

    这是我对这个问题的看法:

        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()
    

    就我而言,我根据我将粘贴到的图像设置img_width, img_height。 你可能会发现很多有趣的使用here的例子。

    另外,svg2png的使用方法如下:

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

    我没有找到详细的description of function svg2png,但是您从参数命名中得出目的。希望有人将其添加到本文中。

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 2011-07-09
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多