如何使用librsvgpython绑定调整svg图像文件的大小
当光栅化svg文件时,我希望能够为生成的png文件设置宽度和高度。在下面的代码中,只有画布设置为所需的宽度和高度,具有原始svg文件维度的实际图像内容呈现在(500600)画布的左上角 我应该怎么做才能使图像内容与cairo canvas大小相同?我试过了如何使用librsvgpython绑定调整svg图像文件的大小,python,cairo,librsvg,Python,Cairo,Librsvg,当光栅化svg文件时,我希望能够为生成的png文件设置宽度和高度。在下面的代码中,只有画布设置为所需的宽度和高度,具有原始svg文件维度的实际图像内容呈现在(500600)画布的左上角 我应该怎么做才能使图像内容与cairo canvas大小相同?我试过了 svg.set_property('width', 500) svg.set_property('height', 500) 但是得到 TypeError: property 'width' is not writable 另外,libr
svg.set_property('width', 500)
svg.set_property('height', 500)
但是得到
TypeError: property 'width' is not writable
另外,librsvg python绑定的文档似乎非常罕见,只有cairo站点上的一些随机代码片段。librsvg中有一个,但它已被弃用
在Cairo中设置以更改图形的大小:
- 在cairo上下文中设置比例变换矩阵
- 使用.render\u cairo()方法绘制SVG
- 将曲面写入PNG
- 这是适合我的代码。
它实现了上面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())
重新缩放已经光栅化的图像是否会导致原始矢量图像的数据丢失?开罗变换矩阵对设置后绘制的矢量数据进行操作。您不会缩放光栅化图像,而是使用librsvg发出的命令来生成它。是否要发布代码片段?您链接的文档是针对C的,Python等效语法并不明显,特别是在处理矩阵和转换时。此外,缩放似乎总是通过一个
因子
,而不是直接到(x,y)
维度重缩放
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())