PyQT (+WebKit) でサムネイル保存する方法

Webページのサムネイルを取る方法、
Firefoxを起動してスクリーンキャプチャを取るとか、
他のソフトを使うとか、色いろ方法はあったみたいなんだけど、
Linux環境で、メッセージサーバーから読み込んで、マルチスレッドでサムネイルを効率よく自前で生成したかったので調べてた。
そしたらQtにWebkitが含まれてて、それ使えばできそうだと判明したので、テストコードを書いてみた。

僕の環境では以下でうまくできました。
Flashを有効にしたい場合は、最初に

QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True);

をしておくと良いみたい。
まだこちらは試してない。

以下サンプルコード。
中途半端なテストコードからでっち上げたけど、ちゃんと動くと思います。
あ、PILも使ってます。

#!/usr/bin/env python

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

from PIL import Image

import tempfile

app = QApplication([])

size = 1024 , 1024

class Thumbnailer(object):
    def __init__(self):
        self.web = QWebPage()

    def render(self, url):
        self.web.mainFrame().load(QUrl(url))
        QObject.connect(self.web, SIGNAL("loadFinished(bool)"), self.onLoadFinished)

    def onLoadFinished(self, *args):
        self.web.setViewportSize(QSize(*size))
        self.web.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff);
        self.web.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff);

        qimage = QImage(size[0], size[1], QImage.Format_ARGB32)
        painter = QPainter(qimage)

        _, tmpfile_name = tempfile.mkstemp(suffix= '.png')
        tmpfile = open(tmpfile_name , 'w+b')
        fn = QString(tmpfile_name)
        self.web.mainFrame().render(painter)
        painter.end()
        qimage.save(fn)
        tmpfile.close()

        im = Image.open(tmpfile_name)
        im.thumbnail((200, 400), Image.ANTIALIAS)
        im.save('test.png')

        app.quit()

t = Thumbnailer()
t.render(sys.argv[1])
app.exec_()

例外処理とか、テンポラリファイル消してないとか、適当だけど、とりあえずメモメモ。


はてな記法とか、いろいろあるのねー。
とりあえずいろんな小ネタをためていこうっと。

サンプルコードみたいの、残しておかないとだめだなぁ。
今回も適当なのしか残ってなかった。。