当栅格化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绑定的文档似乎非常稀少,只有开罗网站上的一些随机代码片段。
发布于 2009-07-27 10:12:28
在librsvg中有一个resize function,但它已被弃用。
在Cairo中设置scale matrix以更改图形的大小:
发布于 2014-10-01 11:30:09
这就是为我工作的代码。它实现了上面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())https://stackoverflow.com/questions/1187358
复制相似问题