Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
When rasterizing svg file, I would like to be able to set width and height for the resulting png file. With the following code, only the canvas is set to the desired width and height, the actual image content with the original svg file dimension is rendered in the top left corner on the (500, 600) canvas.
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")
What should I do to make the image content same size with cairo canvas? I tried
svg.set_property('width', 500)
svg.set_property('height', 500)
but got
TypeError: property 'width' is not writable
Also documents for librsvg python binding seem to be extremely rare, only some random code snippets on cairo site.
There is a resize function in librsvg, but it is deprecated.
Set up a scale matrix in Cairo to change the size of your drawing:
setup a scale transformation matrix on your cairo context
draw your SVG with the .render_cairo() method
write your surface to PNG
–
–
–
# 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())
Resizing svg files programmatically is not obvious. The solution provided here by other answers may be outdated/difficult to implement. I'm using another library svgutils.
The following should work.
import svgutils.transform as sg
import sys
fig = sg.fromfile('myimage.svg')
fig.set_size(('200','200'))
fig.save('myimage2.svg')
You can install svgutils with usual -
pip install svgutils
Once you have properly resized svg file, you can use ffmpeg or any other image converter to save it into png.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.