[PyQt] images aren't saved with this webcapturing script

Victor Noagbodji noagbodjivictor at gmail.com
Sun Nov 22 04:39:10 GMT 2009


hello

i have ported the webcapture code in qt graphics dojo labs to pyqt
(http://qt.gitorious.org/qt-labs/graphics-dojo/trees/master/webcapture)

please find the whole source below. the problem i'm having is that all
my images are replaced with a small blue box with a question mark
within. i have no clue about why that is happening. please help.

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *


qtversion = QT_VERSION_STR.split('.')
not_yet_qt_4_5 = len(qtversion) == 3 and qtversion < (4, 5, 0)


class WebCapture(QObject):
    def __init__(self):
        super(WebCapture, self).__init__()
        self.m_zoom = 100
        self.m_percent = 0
        self.m_page = QWebPage()

        self.connect(
            self.m_page,
            SIGNAL('loadFinished(bool)'),
            self.save_result
        )

        self.connect(
            self.m_page,
            SIGNAL('loadProgress(int)'),
            self.show_progress
        )

    def load(self, url, zoom, output, width):
        print 'Loading', url.toString()
        self.m_zoom = zoom
        self.m_filename = output
        self.m_page.mainFrame().load(url)

        self.m_page.mainFrame().setScrollBarPolicy(
            Qt.Vertical,
            Qt.ScrollBarAlwaysOff
        )

        self.m_page.mainFrame().setScrollBarPolicy(
            Qt.Horizontal,
            Qt.ScrollBarAlwaysOff
        )

        factor = self.m_zoom / 100.0
        size = QSize(width, 3 * width / 4)

        if not_yet_qt_4_5:
            self.m_page.setViewportSize(size / factor)
        else:
            self.m_page.mainFrame().setZoomFactor(factor)
            self.m_page.setViewportSize(size)

    def show_progress(self, percent):
        if self.m_percent >= percent:
            return
        while self.m_percent < percent:
            self.m_percent += 1
            sys.stdout.write('#')
            sys.stdout.flush()

    def save_result(self, ok):
        if not ok:
            sys.stderr.write(
                'Failed loading %s' %
                self.m_page.mainFrame().url().toString()
            )
            self.emit(SIGNAL('done'))
            return

        size = self.m_page.mainFrame().contentsSize()
        image = QImage(size, QImage.Format_ARGB32_Premultiplied)
        image.fill(Qt.transparent)

        p = QPainter(image)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setRenderHint(QPainter.TextAntialiasing, True)
        p.setRenderHint(QPainter.SmoothPixmapTransform, True)
        self.m_page.setViewportSize(self.m_page.mainFrame().contentsSize())
        self.m_page.mainFrame().render(p)
        p.end()

        if not_yet_qt_4_5:
            factor = self.m_zoom / 100.0
            image = image.scaled(
                size * factor,
                Qt.IgnoreAspectRatio,
                Qt.SmoothTransformation
            )

        image.save(self.m_filename)
        self.emit(SIGNAL('done'))


def guess_url_from_string(s):
    urlstr = s.trimmed()
    test = QRegExp('^[a-zA-Z]+\\:.*')

    # check if it looks like a qualified URL. try parsing it and see.
    has_schema = test.exactMatch(urlstr)
    if has_schema:
        url = QUrl(urlstr, QUrl.TolerantMode)
        if url.isValid():
            return url

    # might be a file.
    if QFile.exists(urlstr):
        return QUrl.fromLocalFile(urlstr)

    # might be a shortcut - try to detect schema.
    if not has_schema:
        dot_index = urlstr.indexOf('.')
        if dot_index != -1:
            prefix = urlstr.left(dot_index).toLower()
            schema = prefix if prefix == QString('ftp') else QString('http')
            url = QUrl(schema + QString('://') + urlstr, QUrl.TolerantMode)
            if url.isValid():
                return url

    # fall back to QUrl's own tolerance parser.
    return QUrl(s, QUrl.TolerantMode)

usage = """
Capture a web page and save it as an image
    webcapture url zoom outputfile [viewport width]

Notes:
    "zoom" specifies the zoom factor in percent, default is 100%
    "viewport width" defaults to 1024 (pixels)

Examples:
    webcapture www.trolltech.com 50 trolltech.png 800
    webcapture www.nokia.com 25 nokia.png
"""

if __name__ == '__main__':
    argc = len(sys.argv)

    if argc < 4 or argc > 5:
        print usage
        sys.exit(1)

    url = guess_url_from_string(QString(sys.argv[1]))
    zoom = max(10, QString(sys.argv[2]).toInt()[0])
    filename = QString(sys.argv[3])
    width = 1024 if argc < 5 else QString(sys.argv[4]).toInt()[0]

    app = QApplication(sys.argv)
    capture = WebCapture()
    QObject.connect(
        capture,
        SIGNAL('done'),
        QApplication.instance(),
        SLOT('quit()')
    )
    capture.load(url, zoom, filename, width)
    sys.exit(app.exec_())

-- 
paul victor noagbodji


More information about the PyQt mailing list