summaryrefslogtreecommitdiffstats
path: root/svg2png/svg2png.cpp
blob: 91fee0851dd0d742d772d517cfc505c3891ef6a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Graphics Dojo project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "svg2png.h"

#include <iostream>

#include <QtGui>
#include <QtWebKit>

// large enough to enclose the SVG icons
#define MAGIC_SIZE 4095

WebKitSVGRenderer::WebKitSVGRenderer(QWidget *parent) : QWebView(parent)
{
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(saveResult(bool)));
    setFixedSize(MAGIC_SIZE, MAGIC_SIZE);

    QPalette pal = palette();
    pal.setColor(QPalette::Background, Qt::transparent);
    setPalette(pal);
}

#define EVAL_JS(x) page()->mainFrame()->evaluateJavaScript((x))

void WebKitSVGRenderer::saveResult(bool ok)
{
    // crude error-checking
    if (!ok) {
        std::cerr << "Failed loading " << qPrintable(url().toString()) << std::endl;
        QApplication::instance()->exit(1);
        return;
    }

    // ensure it is an SVG
    QString root = EVAL_JS("document.rootElement.nodeName").toString();
    if (root.isEmpty() || root.compare("svg", Qt::CaseInsensitive)) {
        std::cerr << "Not an SVG! " << qPrintable(url().toString()) << std::endl;
        close();
        return;
    }

    // get the dimension, i.e. the width and height attributes
    // Note: if an attribute is not defined WebKit would return the view's dimension
    // hence the hack of checking for the MAGIC_SIZE
    double ww = EVAL_JS("document.rootElement.width.baseVal.value").toDouble();
    double hh = EVAL_JS("document.rootElement.height.baseVal.value").toDouble();
    if (ww == 0.0 || hh == 0.0 || ww == MAGIC_SIZE || hh == MAGIC_SIZE) {
        std::cerr << "SVG does not specify proper width and height! " << std::endl;
        close();
        return;
    }

    // try to give the best output file
    if (fileName.isEmpty()) {
        fileName = QFileInfo(url().path()).completeBaseName();
        if (fileName.isEmpty())
            fileName = "result";
        fileName += ".png";
    }

    // create the target surface
    QSize t = targetSize.isValid() ? targetSize : QSize(ww, hh);
    QImage img(t, QImage::Format_ARGB32_Premultiplied);
    img.fill(Qt::transparent);

    // prepare the painter
    QPainter p(&img);
    qreal xs = targetSize.isValid() ? targetSize.width() / ww : 1.0;
    qreal ys = targetSize.isValid() ? targetSize.height() / hh : 1.0;
    p.scale(xs, ys);

    // the best quality
    p.setRenderHint(QPainter::Antialiasing);
    p.setRenderHint(QPainter::TextAntialiasing);
    p.setRenderHint(QPainter::SmoothPixmapTransform);

    page()->mainFrame()->render(&p);
    p.end();

    if (img.save(fileName, "png"))
        std::cout << "Result saved to " << qPrintable(fileName) << std::endl;
    else
        std::cout << "Failed to save to " << qPrintable(fileName) << std::endl;

    close();
}

static void usage()
{
    std::cout << "Rasterize an SVG icon to a PNG image" << std::endl << std::endl;
    std::cout << "  svg2png  input.svg [output.png [width height]]" << std::endl << std::endl;
    std::cout << "Examples: " << std::endl;
    std::cout << "  svg2png tiger.svg" << std::endl;
    std::cout << "  svg2png icon.svg icon.png 256 256" << std::endl;
    std::cout << std::endl;
}

int main(int argc, char * argv[])
{
    if ((argc < 2) || (argc == 4)) {
        usage();
        return 0;
    }

    QApplication a(argc, argv);

    WebKitSVGRenderer renderer;
    if (argc < 3)
        renderer.fileName = QString::fromLatin1(argv[2]);
    if (argc == 5) {
        int w = QString::fromLatin1(argv[3]).toInt();
        int h = QString::fromLatin1(argv[4]).toInt();
        renderer.targetSize = QSize(w, h);
        if (!renderer.targetSize.isValid() || w <= 0 || h <= 0) {
            std::cerr << "Please specify a valid target size !" << std::endl;
            return 0;
        }
    }

    QString str = QFileInfo(QString::fromLatin1(argv[1])).absoluteFilePath();
    renderer.load(QUrl::fromLocalFile(str));

    return a.exec();
}