Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a scaled SVG to a QImage?

Tags:

image

svg

qt

There is a QSvgRenderer class in QtSvg module which can render image onto QPaintDevice. This one can be QImage. In that case we will create:

Image svgBufferImage(renderer.defaultSize(), QImage::Format_ARGB32); 

But how to render to a QImage of different size than default from the SVG renderer? Since the SVG format image can be scaled without quality loss, is it possible to generate static images, like PNG, from SVG files using QSvgRenderer?

Does anyone have a better idea? Basically I need to create images like PNG from SVG files in different sizes.

like image 249
Franki Avatar asked Dec 18 '11 12:12

Franki


People also ask

How do I save a SVG file as a high quality PNG?

svg file, right click on it and click on the context menu item 'Save SVG as PNG. Lets you click on the extension icon or right click on an . svg file and choose Save SVG as PNG. You will be able to specify the desired width of the rendered PNG image.

Can svgs have images?

Scalable Vector Graphics (SVG) is a web-friendly vector file format. As opposed to pixel-based raster files like JPEGs, vector files store images via mathematical formulas based on points and lines on a grid.


2 Answers

Just give your QImage the desired size. The SVG renderer will scale to fit the whole image.

#include <QApplication> #include <QSvgRenderer> #include <QPainter> #include <QImage>  // In your .pro file: // QT += svg   int main(int argc, char **argv) {     // A QApplication instance is necessary if fonts are used in the SVG     QApplication app(argc, argv);      // Load your SVG     QSvgRenderer renderer(QString("./svg-logo-h.svg"));      // Prepare a QImage with desired characteritisc     QImage image(500, 200, QImage::Format_ARGB32);     image.fill(0xaaA08080);  // partly transparent red-ish background      // Get QPainter that paints to the image     QPainter painter(&image);     renderer.render(&painter);      // Save, image format based on file extension     image.save("./svg-logo-h.png"); } 

This will create an 500x200 PNG image from the passed in SVG file.

Example output with an SVG image from the SVG logos page:

enter image description here

like image 53
Mat Avatar answered Oct 04 '22 00:10

Mat


Here is complete answer:

QImage QPixmap::toImage()  

If the pixmap has 1-bit depth, the returned image will also be 1 bit deep. Images with more bits will be returned in a format closely represents the underlying system. Usually this will be QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without alpha.

QImage img = QIcon("filepath.svg").pixmap(QSize(requiredsize)).toImage() 

Also copy from above answer

// Save, image format based on file extension image.save("./svg-logo-h.png"); 
like image 42
Yash Avatar answered Oct 03 '22 22:10

Yash