如何使用librsvg Python绑定调整svg图像文件大小
在将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")
我该怎么做才能让图像内容和cairo画布的大小一致呢?我试过
svg.set_property('width', 500)
svg.set_property('height', 500)
但是得到了
TypeError: property 'width' is not writable
另外,关于librsvg的Python绑定的文档似乎非常稀少,只有一些在cairo网站上的随机代码片段。
3 个回答
2
程序matically调整svg文件的大小并不是一件简单的事情。这里其他答案提供的解决方案可能已经过时或者难以实现。我正在使用另一个库svgutils。
下面的代码应该可以工作。
import svgutils.transform as sg
import sys
fig = sg.fromfile('myimage.svg')
fig.set_size(('200','200'))
fig.save('myimage2.svg')
你可以通过常规方式安装svgutils -
pip install svgutils
一旦你正确调整了svg文件的大小,就可以使用ffmpeg或者其他任何图像转换工具把它保存为png格式。
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())