Exemple #1
0
 def __call__(self, ok):
     from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer
     try:
         if not ok:
             raise RuntimeError('Rendering of HTML failed.')
         de = self.page.mainFrame().documentElement()
         pe = de.findFirst('parsererror')
         if not pe.isNull():
             raise ParserError(pe.toPlainText())
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(96*(100/2.54))
         image.setDotsPerMeterY(96*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         ba = QByteArray()
         buf = QBuffer(ba)
         buf.open(QBuffer.WriteOnly)
         image.save(buf, 'JPEG')
         self.data = str(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
Exemple #2
0
 def __call__(self, ok):
     from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer
     try:
         if not ok:
             raise RuntimeError('Rendering of HTML failed.')
         de = self.page.mainFrame().documentElement()
         pe = de.findFirst('parsererror')
         if not pe.isNull():
             raise ParserError(pe.toPlainText())
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(96*(100/2.54))
         image.setDotsPerMeterY(96*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         ba = QByteArray()
         buf = QBuffer(ba)
         buf.open(QBuffer.WriteOnly)
         image.save(buf, 'JPEG')
         self.data = str(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
Exemple #3
0
def image_to_data(image):  # {{{
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    if not image.save(buf, CACHE_FORMAT):
        raise EncodeError('Failed to encode thumbnail')
    ret = bytes(ba.data())
    buf.close()
    return ret
Exemple #4
0
def image_to_data(image):  # {{{
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    if not image.save(buf, CACHE_FORMAT):
        raise EncodeError('Failed to encode thumbnail')
    ret = bytes(ba.data())
    buf.close()
    return ret
Exemple #5
0
def pixmap_to_data(pixmap, format='JPEG', quality=90):
    '''
    Return the QPixmap pixmap as a string saved in the specified format.
    '''
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    pixmap.save(buf, format, quality=quality)
    return bytes(ba.data())
Exemple #6
0
def pixmap_to_data(pixmap, format='JPEG', quality=90):
    '''
    Return the QPixmap pixmap as a string saved in the specified format.
    '''
    ba = QByteArray()
    buf = QBuffer(ba)
    buf.open(QBuffer.WriteOnly)
    pixmap.save(buf, format, quality=quality)
    return bytes(ba.data())
Exemple #7
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
Exemple #8
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
Exemple #9
0
def to_png(bmp):
    # ImageMagick does not convert some bmp files correctly, while Qt does,
    # so try Qt first. See for instance:
    # https://bugs.launchpad.net/calibre/+bug/934167
    # ImageMagick bug report:
    # http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=20350
    from PyQt4.Qt import QImage, QByteArray, QBuffer
    i = QImage()
    if i.loadFromData(bmp):
        ba = QByteArray()
        buf = QBuffer(ba)
        buf.open(QBuffer.WriteOnly)
        i.save(buf, 'png')
        return bytes(ba.data())

    from calibre.utils.magick import Image
    img = Image()
    img.load(bmp)
    return img.export('png')
Exemple #10
0
def to_png(bmp):
    # ImageMagick does not convert some bmp files correctly, while Qt does,
    # so try Qt first. See for instance:
    # https://bugs.launchpad.net/calibre/+bug/934167
    # ImageMagick bug report:
    # http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=20350
    from PyQt4.Qt import QImage, QByteArray, QBuffer

    i = QImage()
    if i.loadFromData(bmp):
        ba = QByteArray()
        buf = QBuffer(ba)
        buf.open(QBuffer.WriteOnly)
        i.save(buf, "png")
        return bytes(ba.data())

    from calibre.utils.magick import Image

    img = Image()
    img.load(bmp)
    return img.export("png")
 class QtCompressor(object):
     def __init__(self, fileName):
         # fileName = os.path.splitext(fileName)[0] + ".qz"
         self.fileName = fileName
         self.byteArray = QByteArray()
     def toHexStr(self, i):
         s = hex(i)
         k = 10 - len(s)
         return s[0:2] + "0"*k + s[2:]
     def write(self, src, arcName):
         g = open(src, "rb")
         data = g.read()
         g.close()
         self.byteArray.append(self.toHexStr(len(arcName)))
         self.byteArray.append(arcName)
         self.byteArray.append(self.toHexStr(len(data)))
         self.byteArray.append(data)
     def close(self):
         f = open(self.fileName, "wb")
         # don't use compression, because resource files are compressed by Qt anyway
         data = self.byteArray.data() #data = qCompress(self.byteArray, 9).data()
         f.write(data)
         f.close()
Exemple #12
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())
        has_alpha = has_mask = False
        soft_mask = mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)
            has_mask = bool(vals)
            vals.discard(0)
            has_alpha = bool(vals)

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)
        elif has_mask:
            # dither the soft mask to 1bit and add it. This also helps PDF
            # viewers without transparency support
            bytes_per_line = (w + 7) >> 3
            mdata = bytearray(0 for i in xrange(bytes_per_line * h))
            spos = mpos = 0
            for y in xrange(h):
                for x in xrange(w):
                    if sdata[spos]:
                        mdata[mpos + x>>3] |= (0x80 >> (x&7))
                    spos += 1
                mpos += bytes_per_line
            mdata = bytes(mdata)
            mask = self.write_image(mdata, w, h, 1)

        return self.write_image(data, w, h, 32, mask=mask, dct=True,
                                    soft_mask=soft_mask, cache_key=cache_key)
Exemple #13
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2
                and img.colorTable().at(0) == QColor(Qt.black).rgba()
                and img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())
        has_alpha = has_mask = False
        soft_mask = mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4 * w * h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)
            has_mask = bool(vals)
            vals.discard(0)
            has_alpha = bool(vals)

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)
        elif has_mask:
            # dither the soft mask to 1bit and add it. This also helps PDF
            # viewers without transparency support
            bytes_per_line = (w + 7) >> 3
            mdata = bytearray(0 for i in xrange(bytes_per_line * h))
            spos = mpos = 0
            for y in xrange(h):
                for x in xrange(w):
                    if sdata[spos]:
                        mdata[mpos + x >> 3] |= (0x80 >> (x & 7))
                    spos += 1
                mpos += bytes_per_line
            mdata = bytes(mdata)
            mask = self.write_image(mdata, w, h, 1)

        return self.write_image(data,
                                w,
                                h,
                                32,
                                mask=mask,
                                dct=True,
                                soft_mask=soft_mask,
                                cache_key=cache_key)