如何使用librsvg Python绑定调整svg映像文件的大小

btw*_*tw0 5 python cairo librsvg

当光栅化svg文件时,我希望能够为生成的png文件设置宽度和高度.使用以下代码,仅将画布设置为所需的宽度和高度,具有原始svg文件尺寸的实际图像内容将呈现在(500,600)画布的左上角.

import cairo
import rsvg

WIDTH, HEIGHT  = 500, 600
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)

ctx = cairo.Context(surface)

svg = rsvg.Handle(file="test.svg")
svg.render_cairo(ctx)

surface.write_to_png("test.png")
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能使图像内容与cairo canvas相同?我试过了

svg.set_property('width', 500)
svg.set_property('height', 500)
Run Code Online (Sandbox Code Playgroud)

但得到了

TypeError: property 'width' is not writable
Run Code Online (Sandbox Code Playgroud)

librsvg python绑定的文档似乎非常罕见,只有一些随机代码片段在cairo网站上.

Lup*_*uch 6

librsvg中有一个resize函数,但不推荐使用它.

在Cairo中设置比例矩阵以更改图形的大小:

  • 在cairo上下文中设置比例变换矩阵
  • 使用.render_cairo()方法绘制SVG
  • 写你的表面到PNG

  • cairo变换矩阵对设置后绘制的矢量数据进行操作.您不缩放光栅化图像,而是缩放由生成它的librsvg发出的命令. (3认同)
  • 重新缩放已经光栅化的图像会导致原始矢量图像的数据丢失吗? (2认同)
  • 小心发布代码片段?您链接的文档是针对C的,Python等效语法并不明显,特别是在处理矩阵和转换时.此外,缩放似乎总是由"因子",而不是直接到"(x,y)"维度重新缩放 (2认同)

Wil*_*ill 5

这是适合我的代码。它实现了上面 Luper 的答案:

import rsvg
import cairo

# Load the svg data
svg_xml = open('topthree.svg', 'r')
svg = rsvg.Handle()
svg.write(svg_xml.read())
svg.close()

# Prepare the Cairo context
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 
      WIDTH, 
      HEIGHT)
ctx = cairo.Context(img)

# Scale whatever is written into this context
# in this case 2x both x and y directions
ctx.scale(2, 2)
svg.render_cairo(ctx)

# Write out into a PNG file
png_io = StringIO.StringIO()
img.write_to_png(png_io)    
with open('sample.png', 'wb') as fout:
    fout.write(png_io.getvalue())
Run Code Online (Sandbox Code Playgroud)