def add_record_to_variable_table(self, record: GroupedVariableRecord, row: int = None):  # , verbose: bool = False):
        """Add record to variable table"""
        tbl = self.variables_tbl

        column = self.table_info('column')

        # This will add a row
        if row is None:
            row = tbl.rowCount()

        img = QImage.fromData(record.image)
        pixmap = QPixmap.fromImage(img)
        lbl = QLabel()
        lbl.setPixmap(pixmap)
        tbl.setCellWidget(row, column['var_image'], lbl)
        tbl.setItem(row, column['var_name'], QTableWidgetItem(record.name))
        tbl.setItem(row, column['dimension'], QTableWidgetItem(str(record.dimensions)))

        un_id_for_var = record.unit_id

        unit = self.unit.all_records[un_id_for_var]
        if unit.image is not None:
            img = QImage.fromData(unit.image)
            pixmap = QPixmap.fromImage(img)
            lbl = QLabel()
            lbl.setPixmap(pixmap)
            tbl.setCellWidget(row, column['unit_image'], lbl)
        tbl.setItem(row, column['unit_name'], QTableWidgetItem(unit.name))
Beispiel #2
0
 def init(cls):
     cls.Types[cls.Info] = QPixmap(
         QImage.fromData(
             base64.b64decode(
                 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAC5ElEQVRYR8VX0VHbQBB9e/bkN3QQU0FMBSEVYFcQ8xPBJLJ1FWAqOMcaxogfTAWQCiAVRKkgTgfmM4zRZu6QhGzL0p0nDPr17e7bt7tv14RX/uiV48MJgAon+8TiAMRtMFogaqUJxADPwRRzg67kl8+xbWJWANR40iPQSSFgtX/mGQkaDr56V3VAKgGos4s2JXwJoF3naMPvMS+SrpTHs032GwGkdF+DsFMVnJm/oyGGeHico0EjIjpYes+YMyVd6R/flfkpBWCCQ9zaZM2LZDfLMGXsZ5kdI/lYBmINgHHyyLd1mWdBbAFAM/GY7K2WYx1AeB4T6L1N9umbGxZ0qktATaEAdCps48D39oq/LwEw3U5CN92LfczJoewfT7MAywDCaEbAuxeLrh0zz4L+0e4aAJfGy+sP3IMxlH1vpMJoSMCJDXgWtJeJVc6ACs9HBBrYODCJAFdYvAmkPJxnNqMwYht7Bn+T/lGg3z4DGEd3RPhQ54DBvwAOVkeqagRXfTLjh+x7+8sALOtfHLuiYzWOAiLoKbD58mnIGbCmLxUepS6NQmYlUGE0JeCTTXT9JvA9E9sZgO5iIpoyc6/YzcqSwQzgGgBXB7oXpH9klpRSkxY1xW/b7Iu2zk34PILPnazCqEPAtTWA8iZ0HsOu9L0bw4DzCJeNocMGNDpQ3IKO+6NUiJ4ysZNiBv5I3zPnmJmG5oM+wbS+9+qkvGi7NAXGmeUy0ioofa+XA0jH0UaMKpdRWs/adcwMqfV/tenqpqHY/Znt+j2gJi00RUzA201dXaxh9iZdZloJS+9H1otrkbRrD5InFqpPskxEshJQ468CkSmJC+i1HigaaxCAuCljgoDhwPdOjf7rFVxxuJrMkXScjtKc1rOLNpJk6nii5XmYzbngzlZn+RIb40kPJPTBYXUt6VEDJ8Pi6bWpNFb/jFYY6YGpDeKdjBmTKdMcxDGEmP73v2a2Gr/NOycGtglQZ/MPzEqCMLGckJEAAAAASUVORK5CYII='
             )))
     cls.Types[cls.Success] = QPixmap(
         QImage.fromData(
             base64.b64decode(
                 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACZUlEQVRYR8VXS3LTQBDtVsDbcAPMCbB3limkcAKSG4QFdnaYE2BOQLKzxSLJCeAGSUQheSnfwLmB2VJhXmpExpFHI2sk2RWv5FJPv9evP9NieuIfPzE+VSJw8qt3IMDvmahDoDYxt2UAACXMWIIowR5ffn8TJbaBWRE4CXvHAH9RgKXOgQUI48CfXZbZbiTw8Xe/w3d0zkydMkem91IZpyWOJu5sUXS+kEAqt3B+MNOLOuDqDEBLxxFHk7eza5MfIwEJDjhXTYD1s8zinYlEjsCD7FdNI9cJpEq0RFdPR47AMOzLCn69zegz6UgCP+pmfa8RSKudnPNdgCufTOLDxJtdPP7PoA1Cd8HEL5sSUCCD0B0x8bc1f8Bi6sevcgS2VXh6hMOwDz0gsUddNaxWKRjeuKfE/KlJ9Dq4UYH/o/Ns6scj+bgiMAjdayb26xLQwTfVEwg3gRcf6ARq578KuLo7VDc8psCQqwfjr4EfjYvkrAquFJ56UYpdSkAZSmNd1rrg0leOQFELgvA58OJTxVyRaAJORPOpF6UXnFUR5sDiXjs7UqsOMGMRlrWhTkJXpFL3mNrQZhA1lH3F0TiI5FurUQyMpn58VjhkSqQA4Tbw4nSVW6sBU5VXktXSeONlJH3s8jrOVr9RgVSFuNcWfzlh5n3LoKzMAPxxWuiULiQpiR2sZNnCyzIuWUr5Z1Ml0sgdHFZaShVDuR86/0huL3VXtDk/F4e11vKsTHLSCeKx7bYkW80hjLOrV1GhWH0ZrSlyh2MwdZhYfi8oZeYgLBmUiGd8sfVPM6syr2lUSYGaGBuP3QN6rVUwYV/egwAAAABJRU5ErkJggg=='
             )))
     cls.Types[cls.Warning] = QPixmap(
         QImage.fromData(
             base64.b64decode(
                 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACmElEQVRYR8VXTW7TUBD+xjYSXZFukOIsSE9AskNJJMoJmq4r7OYEwAkabhBOkB/Emt4gVIojdpgbpIumEitX6gKB7UHPkauXxLHfc4F6Z3l+vvnmm/fGhAd+6IHzQwvA9cfOITMfAdQAcx1EdVEAM/tEFADsWyaPn57MfdXClABcT1qnzHSWJiwMzrwgoF91vXGRbS6AH59ajd8hDYmoURQo67tgxoij42rv62KX/04Agu44xmciVMokT32YERgGjquvZ1+y4mQCWPUa0/sk3vQlwqssEFsAVrQbU4XKL/ai2+5PPK6waQ4AOsoDnDARh83NdmwBuJq0fQI9L6p+L7rd3+/5gbAToMPI+FbkIzRRc72mbLcGIFE7jGFRIPHddmZrvstJh1X8CHGv6sxHqe1GkPYCoGcqgcoCAPPCdr2DLQC6wqMoPEj7qdqCNKllxs30sLpjYDluDUDGG5XqhY2sal3w4PiD7c7fJnHShMtJR8zpy/8CALiwndnhBgD1/t+XAXkaZAaUVHwnHulg0W6BNEWlAQD8zna8gQB0Ne70iXCm2j55jCUAei1gxvuaO+uXAcDg7zXHSy640iKUAehOEDJFqDmGQkiPLO5Fv+KADXOqvCuIsrPGsIyQdHou22YeRMJgOdHTQTkAfGk7XrLKrWlAvOhcRgBfWiZ3RQti0zxXuUFXCXMuo0TRitfxugjbIxC5RYzI6s9kIGFh+KLOpiW22id5AUuI8IaisFG4kCQg/sFKJgtPLix3KWXGeRETRbQDuCFCV2spTYMm+2FEI1WBbYIRPTeiqFtqLZeDraaD+qrbkpgQAvfl1WsXU0p/RjIjYYhTkNFgcCVlRlRKoAAc+5aF0V//NVPoc2kTLQZKZ8lx/AMXBmMwuXUwOAAAAABJRU5ErkJggg=='
             )))
     cls.Types[cls.Error] = QPixmap(
         QImage.fromData(
             base64.b64decode(
                 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACrklEQVRYR82XW27aQBSG/4PtiNhIpStouoImKwjZAV1B07coWCpZQcgK6kh2lLeSFZSsIOwgdAdkBaUSEBQDpxpjU9vM+EJR03nDzJz/mzm3GcIrD3plfZQCeD47O1ho2jERNRmoE9AQG2BgBGBAwIiZe5Zh3JPjiG+5oxCAEF5q2iWITnMtRhOYu5XF4mr/9naYtSYXYGLbHQCXhYVTEwlom657rVqvBOB2uz71/a+ldq1SYe6ahnEhc4sSYGzbfQKOt915eh0D/ZrrnqS/SwEmrVYXRJ92Jb4OC+C65rrtuN0NgIltNwF837V4zN5Hy3V70e9NgFZrCKJ3CQDmJ9MwDsW36XzeB/AhA/CHqeuN2WxWX2paX2JraHneeynA+Pz8lCqVbxLjV5brimxAEJxqiEA8CjZVBvFy+bl2c9MV9hInoAw85qFpGEeRYQVEQjzMokcQHWxsiPne8jzh6j8AodGfyqNlHpiGcaKAkIk/gChwm2yYuv5W2FqfwLNtN5bAQ2bwySB83zENo50A8/1McaFRAU72XVek+mpk+D/JlIKI/xkee654uCbIhjVAqZIrgSgpLhiCwN4OAEj4vEB2yDybBCjsAol4ZD0nRdMQSRcUCsKUeNSw4o2mKMRGEOamoVx8FXDZKVosDYNMUHXAsBRnppo8RQcbpTgIGEkhykpFjnWxzGhPQYxt2yHgS/oIlKVYTJxImpG482nz+VG1Wh1N84pMCCGa0ULXHwmoJwCYnyzPW5fn/68dh7EgPbrMMl3gz7gro+n/7EoWD7w4a96l1NnJ1Yz5Lt6wCgFEk0r1CIkbiPnC9DxH5aHcd4FYGD5MOqVOg/muslh0/vphkm63k5eXZvA0I6qD+ZCI3jDzLxANiHn1NNvb6+30aVYgwLeeUsgFW1svsPA3Ncq4MHzVeO8AAAAASUVORK5CYII='
             )))
     cls.Types[cls.Close] = QPixmap(
         QImage.fromData(
             base64.b64decode(
                 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAeElEQVQ4T2NkoBAwUqifgboGzJy76AIjE3NCWmL0BWwumzV/qcH/f38XpCfHGcDkUVwAUsDw9+8GBmbmAHRDcMlheAGbQnwGYw0DZA1gp+JwFUgKZyDCDQGpwuIlrGGAHHAUGUCRFygKRIqjkeKERE6+oG5eIMcFAOqSchGwiKKAAAAAAElFTkSuQmCC'
             )))
    def loadRecentDocuments(self):
        self.recentDocuments = []
        recentDocumentsPaths = self.kritaInstance.recentDocuments()

        for path in recentDocumentsPaths:
            if path:
                thumbnail = None
                extension = Path(path).suffix
                page = None
                if extension == '.kra':
                    page = zipfile.ZipFile(path, "r")
                    thumbnail = QImage.fromData(page.read("mergedimage.png"))
                    if thumbnail.isNull():
                        thumbnail = QImage.fromData(page.read("preview.png"))
                else:
                    thumbnail = QImage(path)

                if thumbnail.isNull():
                    continue

                thumbSize = QSize(200 * self.devicePixelRatioF,
                                  150 * self.devicePixelRatioF)
                if thumbnail.width() <= thumbSize.width() or thumbnail.height(
                ) <= thumbSize.height():
                    thumbnail = thumbnail.scaled(thumbSize, Qt.KeepAspectRatio,
                                                 Qt.FastTransformation)
                else:
                    thumbnail = thumbnail.scaled(thumbSize, Qt.KeepAspectRatio,
                                                 Qt.SmoothTransformation)
                thumbnail.setDevicePixelRatio(self.devicePixelRatioF)
                self.recentDocuments.append(thumbnail)
        self.modelReset.emit()
Beispiel #4
0
def preview_icon(race, gender):
    """Return an icon image for player race/gender previews."""
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    db = assets.Assets(assets_db_file, starbound_folder)
    icon_file = db.species().get_preview_image(race, gender)
    if icon_file is None:
        return QPixmap.fromImage(QImage.fromData(db.missing_icon())).scaledToHeight(48)
    else:
        return QPixmap.fromImage(QImage.fromData(icon_file)).scaledToHeight(48)
Beispiel #5
0
def preview_icon(race, gender):
    """Return an icon image for player race/gender previews."""
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    db = assets.Assets(assets_db_file, starbound_folder)
    icon_file = db.species().get_preview_image(race, gender)
    if icon_file is None:
        return QPixmap.fromImage(QImage.fromData(
            db.missing_icon())).scaledToHeight(48)
    else:
        return QPixmap.fromImage(QImage.fromData(icon_file)).scaledToHeight(48)
Beispiel #6
0
    def paintEvent(self, e):
        #drawing on widget
        if self.env.cmp.dirty:
            cairo = False
            if cairo:
                start_time = time.time()
                self.env.paint(self.cairo_painter)
                print(" %.6f - painting " % (time.time() - start_time))

                start_time = time.time()
                data = self.cairo_painter.get_image_as_byte_data()
                print(" %.6f - converting to bytes " %
                      (time.time() - start_time))

                start_time = time.time()
                self.env_img = QImage.fromData(data)
                print(" %.6f - converting to QImage " %
                      (time.time() - start_time))

                self.draw_image(self.env_img)
            else:
                start_time = time.time()
                self.env.paint(self.qt_painter)
                #print(" %.6f - painting " % (time.time() - start_time))
                self.draw_pixmap(self.qt_painter.get_pixmap())

            self.env.dirty = False

        p = QPainter(self)
        p.drawPixmap(0, 0, self.canvas)
Beispiel #7
0
    def get_favicon(self):
        """
        Get favicon for the site.

        This is called when the site_url can’t be loaded or when that
        page doesn’t contain a link tag with rel set to icon (the new
        way of doing site icons.)
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        ico_url = urllib.parse.urljoin(self.icon_url, "/favicon.ico")
        ico_request = urllib.request.Request(ico_url)
        if self.user_agent:
            ico_request.add_header('User-agent', self.user_agent)
        ico_response = urllib.request.urlopen(ico_request)
        if 200 != ico_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(ico_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        ico_size = self.site_icon.size()
        if ico_size.width() > max_size.width() \
                or ico_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(
                max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
Beispiel #8
0
    def load(self):
        """
        Public method to load the bookmarks.
        """
        if self.__loaded:
            return

        if self.__iconDatabasePath:
            filename = os.path.join(self.__iconDatabasePath,
                                    self.__iconsFileName)
            try:
                f = open(filename, "r")
                db = json.load(f)
                f.close()
            except (IOError, OSError):
                # ignore silentyl
                db = {}

            self.__iconsDB = {}
            for url, data in db.items():
                self.__iconsDB[url] = QIcon(
                    QPixmap.fromImage(
                        QImage.fromData(
                            QByteArray(data.encode(self.__encoding)))))

        self.__loaded = True
Beispiel #9
0
 def gotThumbnail(self):
     if empty(self.movie.thumbnail_url) and self.movie.thumbnail_url != NotAvailable:
         self.backend.fill_movie(self.movie, ('thumbnail_url'))
     if not empty(self.movie.thumbnail_url):
         data = requests.get(self.movie.thumbnail_url).content
         img = QImage.fromData(data)
         self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToHeight(100,Qt.SmoothTransformation))
Beispiel #10
0
    def _load_img(self, img_path):
        try:
            with open(img_path, 'rb') as f:
                img_data = f.read()
        except Exception as e:
            QMessageBox.warning(self, 'Warning', str(e))
            return

        img = QImage.fromData(img_data)
        if img.isNull():
            QMessageBox.warning(self, 'Warning', 'Invalid Image')
            return False

        pixmap = QPixmap.fromImage(img)
        self.curr_img_width = pixmap.size().width()
        self.curr_img_height = pixmap.size().height()
        self.scale_factor = self.ui.doubleSpinBox_resize.value()
        pixmap = pixmap.scaled(int(self.curr_img_width * self.scale_factor),
                               int(self.curr_img_height * self.scale_factor),
                               Qt.KeepAspectRatio)
        #print(pixmap.size())
        print("load_img")
        print(self.imageLabel)
        self.imageLabel.setPixmap(pixmap)
        self.currImg = img_path

        return True
Beispiel #11
0
 def set_tile(self, lett, lliw="black"):
     """ Draw letter on tile """
     if isinstance(lett, list):
         new_data = self.set_hint(lett)
     else:
         new_data = bytearray(Cons.SVG_DATA_1.format(one=lett, col=lliw), 'utf-8')
     return QImage.fromData(new_data, 'SVG')
Beispiel #12
0
    def savePascalVocFormat(self, filename, shapes, imagePath, imageData,
                            lineColor=None, fillColor=None, databaseSrc=None):
        imgFolderPath = os.path.dirname(imagePath)
        imgFolderName = os.path.split(imgFolderPath)[-1]
        imgFileName = os.path.basename(imagePath)
        #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0]

        # Read from file path because self.imageData might be empty if saving to
        # Pascal format
        if imageData is None:
            imageData = read(imagePath)
        image = QImage(imagePath) if imageData is None else QImage.fromData(imageData)

        imageShape = [image.height(), image.width(),
                      1 if image.isGrayscale() else 3]
        writer = PascalVocWriter(imgFolderName, imgFileName,
                                 imageShape, localImgPath=imagePath)
        writer.verified = self.verified

        for shape in shapes:
            points = shape['points']
            label = shape['label']
            # Add Chris
            difficult = int(shape['difficult'])
            bndbox = LabelFile.convertPoints2BndBox(points)
            writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult)

        writer.save(targetFile=filename)
        return
Beispiel #13
0
    def __init__(self, source, zoom, tilex, tiley, idxx, idxy):
        super().__init__()
        self.source = source
        self.zoom = zoom
        self.tilex = tilex
        self.tiley = tiley
        self.idxx = idxx
        self.idxy = idxy
        self.ext = source[source.rfind('.'):]

        self.image = None
        # For the image data, check cache path first
        fpath = path.join(bs.settings.cache_path, source, str(zoom),
                          str(tilex))
        fname = path.join(fpath, f'{tiley}{self.ext}')
        if path.exists(fname):
            self.image = QImage(fname).convertToFormat(QImage.Format_ARGB32)
        else:
            # Make sure cache directory exists
            makedirs(fpath, exist_ok=True)
            for url in bs.settings.tile_sources[source]['source']:
                try:
                    url_request = urlopen(
                        url.format(zoom=zoom, x=tilex, y=tiley))
                    data = url_request.read()
                    self.image = QImage.fromData(data).convertToFormat(
                        QImage.Format_ARGB32)
                    with open(fname, 'wb') as fout:
                        fout.write(data)
                    break
                except URLError as e:
                    print(
                        f'Error loading {url.format(zoom=zoom, x=tilex, y=tiley)}:'
                    )
                    print(traceback.format_exc())
Beispiel #14
0
    def __readImage(self):
        atts = self.xml.attributes()
        source = atts.value("source")
        format = atts.value("format")
        if len(source)==0:
            while (self.xml.readNextStartElement()):
                if (self.xml.name() == "data"):
                    atts = self.xml.attributes()
                    encoding = atts.value("encoding")
                    data = self.xml.readElementText().toLatin1()
                    if (encoding == "base64"):
                        data = QByteArray.fromBase64(data)

                    self.xml.skipCurrentElement()
                    return QImage.fromData(data, format.toLatin1())
                else:
                    self.__readUnknownElement()

        else:
            self.xml.skipCurrentElement()
            source = self.p.resolveReference(source, self.mPath)
            image = self.p.readExternalImage(source)
            if (image.isNull()):
                self.xml.raiseError(self.tr("Error loading image:\n'%s'"%source))
            return image

        return QImage()
Beispiel #15
0
    def display_photo(self):
        if not self.housing.photos:
            self.ui.photosFrame.hide()
            return

        if self.displayed_photo_idx >= len(self.housing.photos):
            self.displayed_photo_idx = len(self.housing.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photosFrame.hide()
            return

        self.ui.photosFrame.show()

        photo = self.housing.photos[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob,
                                                lambda p: self.display_photo())
            self.process_photo[photo.id].do('fillobj',
                                            photo, ['data'],
                                            backends=self.housing.backend)

            return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width() / 3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '<a href="%s">%s</a>' % (photo.url, photo.url)
            self.ui.photoUrlLabel.setText(text)
Beispiel #16
0
    def display_photo(self):
        if self.displayed_photo_idx >= len(self.contact.photos) or self.displayed_photo_idx < 0:
            self.displayed_photo_idx = len(self.contact.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photoUrlLabel.setText('')
            return

        photo = self.contact.photos.values()[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob, lambda p: self.display_photo())
            self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.contact.backend)

            if photo.thumbnail_data:
                data = photo.thumbnail_data
            else:
                return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width()/3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '<a href="%s">%s</a>' % (photo.url, photo.url)
            if photo.hidden:
                text += '<br /><font color=#ff0000><i>(Hidden photo)</i></font>'
            self.ui.photoUrlLabel.setText(text)
Beispiel #17
0
 def clipboard_handler(event):
     if event.key == 'ctrl+c':
         buf = io.BytesIO()
         fig.savefig(buf)
         QApplication.clipboard().setImage(
             QImage.fromData(buf.getvalue()))
         buf.close()
Beispiel #18
0
    def makeRecommendationInfo(self):
        self.recommendations = self.__generateRecommendation()

        pictures = (self.RecommendationPicture1, self.RecommendationPicture2,
                    self.RecommendationPicture3)
        titles = (self.RecommendationTitle1, self.RecommendationTitle2,
                  self.RecommendationTitle3)

        posterFetcher = FilmInterface(False)

        for i in range(3):
            posterFetcher.selectFilm(self.recommendations[i])
            result = posterFetcher.fetchResult()

            if len(result) == 0:
                raise RuntimeError(
                    'the recommendation algorithm has suggested a ghost film')

            name = getColumn(result[0], FILM_TABLE.chineseName)
            url = getColumn(result[0], FILM_TABLE.picture)
            titles[i].setText(name)
            pictures[i].clear()

            if url is not None:
                try:
                    res = getURL(url, timeout=20)
                    if res.status_code != 200:
                        raise RequestException()

                    image = QImage.fromData(res.content)
                    pictures[i].setPixmap(QPixmap.fromImage(image))
                except RequestException:
                    pictures[i].setText('海报加载失败')
            else:
                pictures[i].setText('暂无海报')
Beispiel #19
0
    def get_favicon(self):
        u"""
        Get favicon for the site.

        This is called when the site_url can’t be loaded or when that
        page doesn’t contain a link tag with rel set to icon (the new
        way of doing site icons.)
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        ico_url = urllib.parse.urljoin(self.icon_url, "/favicon.ico")
        ico_request = urllib.request.Request(ico_url)
        if self.user_agent:
            ico_request.add_header('User-agent', self.user_agent)
        ico_response = urllib.request.urlopen(ico_request)
        if 200 != ico_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(ico_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        ico_size = self.site_icon.size()
        if ico_size.width() > max_size.width() \
                or ico_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(
                max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
Beispiel #20
0
    def display_photo(self):
        if not self.housing.photos:
            self.ui.photosFrame.hide()
            return

        if self.displayed_photo_idx >= len(self.housing.photos):
            self.displayed_photo_idx = len(self.housing.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photosFrame.hide()
            return

        self.ui.photosFrame.show()

        photo = self.housing.photos[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob, lambda p: self.display_photo())
            self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.housing.backend)

            return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width()/3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '<a href="%s">%s</a>' % (photo.url, photo.url)
            self.ui.photoUrlLabel.setText(text)
Beispiel #21
0
    def getPix(self, url1, url2=None):
        img1 = self.cache.get_resource(url1)
        i1 = QImage.fromData(img1)
        i1 = i1.scaledToHeight(60, Qt.SmoothTransformation)
        if url2 is not None:
            img2 = self.cache.get_resource(url2)
            i2 = QImage.fromData(img2)
            i2 = i2.scaledToHeight(30, Qt.SmoothTransformation)
            p = QPainter()
            p.begin(i1)
            p.drawImage(0, 30, i2)
            p.end()

        ret = QLabel()
        ret.setPixmap(QPixmap.fromImage(i1))
        return ret
 def run(self):
     try:
         addr = "{server_address}/product/barcode/{ID}/{TYPE}".format(
             **dict(server_address=self.auth.get("server_address"),
                    ID=self.productID,
                    TYPE=self.TYPE))
         print(addr)
         response = self.signals.session.get(
             addr,
             stream=True,
             auth=(self.auth.get("username"), self.auth.get("password")))
         print(response)
         if response.status_code == 200:
             self.imgbio = BytesIO()
             for chunk in response.iter_content(1024):
                 self.imgbio.write(chunk)
             self.imgbio.seek(0)
             pixmap = QPixmap.fromImage(QImage.fromData(self.imgbio.read()))
             self.signals.hasImage.emit(pixmap, self.WHO)
         else:
             raise Exception(str(response.status_code))
     except Exception as e:
         print(e)
         self.signals.hasError.emit(e)
     self.signals.finished.emit()
 def slot_check_for_page_update(self, url):
     if "pages" in self.setupDictionary.keys():
         relUrl = os.path.relpath(url, self.projecturl)
         if relUrl in self.setupDictionary["pages"]:
             index = self.pagesModel.index(self.setupDictionary["pages"].index(relUrl), 0)
             if index.isValid():
                 if os.path.exists(url) is False:
                     # we cannot check from here whether the file in question has been renamed or deleted.
                     self.pagesModel.removeRow(index.row())
                     return
                 else:
                     # Krita will trigger the filesystemwatcher when doing backupfiles,
                     # so ensure the file is still watched if it exists.
                     self.pagesWatcher.addPath(url)
                 pageItem = self.pagesModel.itemFromIndex(index)
                 page = zipfile.ZipFile(url, "r")
                 dataList = self.get_description_and_title(page.read("documentinfo.xml"))
                 if (dataList[0].isspace() or len(dataList[0]) < 1):
                     dataList[0] = os.path.basename(url)
                 thumbnail = QImage.fromData(page.read("preview.png"))
                 pageItem.setIcon(QIcon(QPixmap.fromImage(thumbnail)))
                 pageItem.setText(dataList[0])
                 pageItem.setData(dataList[1], role = CPE.DESCRIPTION)
                 pageItem.setData(relUrl, role = CPE.URL)
                 pageItem.setData(dataList[2], role = CPE.KEYWORDS)
                 pageItem.setData(dataList[3], role = CPE.LASTEDIT)
                 pageItem.setData(dataList[4], role = CPE.EDITOR)
                 self.pagesModel.setItem(index.row(), index.column(), pageItem)
Beispiel #24
0
 def gotThumbnail(self):
     if self.recipe.picture_url and not empty(self.recipe.picture_url):
         data = requests.get(self.recipe.picture_url).content
         img = QImage.fromData(data)
         self.ui.imageLabel.setPixmap(
             QPixmap.fromImage(img).scaledToWidth(250,
                                                  Qt.SmoothTransformation))
Beispiel #25
0
 def gotThumbnail(self):
     if not empty(self.person.thumbnail_url):
         data = urllib.urlopen(self.person.thumbnail_url).read()
         img = QImage.fromData(data)
         self.ui.imageLabel.setPixmap(
             QPixmap.fromImage(img).scaledToWidth(220,
                                                  Qt.SmoothTransformation))
Beispiel #26
0
    def on_treeWidget_imagenamelist_itemDoubleClicked(self, qtreeitem, p_int):

        img_id = int(qtreeitem.text(1))
        key_dict = {'autoid': img_id}
        res = self.IC.get_data(1, False, *VALUE_TUPLE_IM, **key_dict)
        if not len(res):
            return
        ext = res[0]['ext']
        image = res[0]['img']

        if ext.lower() == 'pdf':
            self.comboBox_jumpto.setVisible(True)
            self.pushButton_prepage.setVisible(True)
            self.pushButton_nextpage.setVisible(True)
            self.current_img = fitz.Document(stream=image, filetype='pdf')
            page_count = self.current_img.pageCount
            page_list = []
            self.comboBox_jumpto.clear()
            for i in range(1, page_count + 1):
                page_list.append('第' + str(i) + '页')
            self.comboBox_jumpto.addItems(page_list)
            self.current_page = self.current_img.loadPage(0)

        else:
            self.comboBox_jumpto.setVisible(False)
            self.pushButton_prepage.setVisible(False)
            self.pushButton_nextpage.setVisible(False)
            img = QImage.fromData(image)
            self.current_img = QPixmap.fromImage(img)
            self.label_image.setPixmap(self.current_img)

        # 默认放大为3被,同时自动调用on_horizontalSlider_zoom_valueChanged
        self.horizontalSlider_zoom.setValue(30)
Beispiel #27
0
    def update_item_info(self, name, data):
        merged = {}
        defaults = self.assets.items().get_item(name)
        if defaults is not None:
            merged.update(defaults[0])
        merged.update(data)

        item_info = "<html><body>"
        item_info += generate_item_info(merged)
        item_info += "</body></html>"
        self.ui.desc.setText(item_info)

        inv_icon = self.assets.items().get_item_icon(name)
        image = self.assets.items().get_item_image(name)

        if inv_icon is not None:
            inv_icon = self.assets.images().color_image(inv_icon, data)
            icon = QPixmap.fromImage(ImageQt(inv_icon))
        elif image is not None:
            image = self.assets.images().color_image(image, data)
            icon = QPixmap.fromImage(ImageQt(image))
        else:
            logging.warning("Unable to load image for %s", name)
            icon = QPixmap.fromImage(
                QImage.fromData(self.assets.items().missing_icon()))

        icon = self.scale_image_icon(icon, 64, 64)
        self.ui.icon.setPixmap(icon)
Beispiel #28
0
    def load_img(self, img_id):
        try:
            with open(self.showImages[img_id], 'rb') as f:
                img_data = f.read()
        except Exception as e:
            QMessageBox.warning(self, 'Warning', str(e))
            return

        img = QImage.fromData(img_data)
        if img.isNull():
            QMessageBox.warning(self, 'Warning', 'Invalid Image')
            return False

        pixmap = QPixmap.fromImage(img)
        self.frameWidth = pixmap.size().width()
        self.frameHeight = pixmap.size().height()
        a = self.ui.label_image.size()
        #计算缩放比例
        if a.width() / self.frameWidth < a.height() / self.frameHeight:
            self.scaleFactor = a.width() / self.frameWidth
            self.startx = 0
            self.starty = (a.height() -
                           self.scaleFactor * self.frameHeight) / 2
        else:
            self.scaleFactor = a.height() / self.frameHeight
            self.starty = 0
            self.startx = (a.width() -
                           self.scaleFactor * self.frameWidth) / 2.0

        pixmap = pixmap.scaled(int(self.frameWidth * self.scaleFactor),
                               int(self.frameHeight * self.scaleFactor),
                               Qt.KeepAspectRatio)
        self.ui.label_image.setPixmap(pixmap)
        self.current_img = self.showImages[img_id]
        return True
Beispiel #29
0
 def set_image(self, image_png):
     self.setWindowTitle('错误图片,清晰版看当前目录下的error.png')
     self.label.setScaledContents(True)
     image = QImage.fromData(image_png)
     pixmap = QPixmap()
     pixmap = pixmap.fromImage(QImage=image, flags=None)
     self.label.setPixmap(pixmap)
Beispiel #30
0
 def copy_chart(self):
     """ Copy current chart to clipboard
     """
     buf = io.BytesIO()
     self.figure.savefig(buf, dpi=150)
     QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
     buf.close()
Beispiel #31
0
 def gotThumbnail(self):
     if empty(self.person.thumbnail_url) and self.person.thumbnail_url != NotAvailable:
         self.backend.fill_person(self.person, ('thumbnail_url'))
     if not empty(self.person.thumbnail_url):
         data = urllib.urlopen(self.person.thumbnail_url).read()
         img = QImage.fromData(data)
         self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToHeight(100,Qt.SmoothTransformation))
Beispiel #32
0
    def _dataIcon(self, obj, qidx):
        if qidx.column() != 0:
            return QVariant()

        var = try_get_thumbnail(obj)
        if var:
            return var

        try:
            thumbnail = obj.thumbnail
        except AttributeError:
            return QVariant()
        if thumbnail is NotLoaded:
            self.fillObj(obj, ['thumbnail'], qidx)
        elif thumbnail is NotAvailable:
            return QVariant()
        elif thumbnail.data is NotLoaded:
            self.fillObj(thumbnail, ['data'], qidx)
        elif thumbnail.data is NotAvailable:
            return QVariant()
        else:
            img = QImage.fromData(thumbnail.data)
            store_thumbnail(obj)
            return QVariant(QIcon(QPixmap(img)))

        return QVariant()
Beispiel #33
0
    def __readImage(self):
        atts = self.xml.attributes()
        source = atts.value("source")
        format = atts.value("format")
        if len(source) == 0:
            while (self.xml.readNextStartElement()):
                if (self.xml.name() == "data"):
                    atts = self.xml.attributes()
                    encoding = atts.value("encoding")
                    data = self.xml.readElementText().toLatin1()
                    if (encoding == "base64"):
                        data = QByteArray.fromBase64(data)

                    self.xml.skipCurrentElement()
                    return QImage.fromData(data, format.toLatin1())
                else:
                    self.__readUnknownElement()

        else:
            self.xml.skipCurrentElement()
            source = self.p.resolveReference(source, self.mPath)
            image = self.p.readExternalImage(source)
            if (image.isNull()):
                self.xml.raiseError(
                    self.tr("Error loading image:\n'%s'" % source))
            return image

        return QImage()
Beispiel #34
0
 def gotThumbnail(self):
     if not empty(self.movie.thumbnail_url):
         data = requests.get(self.movie.thumbnail_url).content
         img = QImage.fromData(data)
         self.ui.imageLabel.setPixmap(
             QPixmap.fromImage(img).scaledToWidth(220,
                                                  Qt.SmoothTransformation))
Beispiel #35
0
    def _get_hints_arg(self, *, origin_url: QUrl,
                       icon: QImage) -> Dict[str, Any]:
        """Get the hints argument for present()."""
        origin_url_str = origin_url.toDisplayString()
        hints: Dict[str, Any] = {
            # Include the origin in case the user wants to do different things
            # with different origin's notifications.
            "x-qutebrowser-origin": origin_url_str,
            "desktop-entry": "org.qutebrowser.qutebrowser",
        }

        is_useful_origin = self._should_include_origin(origin_url)
        if self._capabilities.kde_origin_name and is_useful_origin:
            hints["x-kde-origin-name"] = origin_url_str

        if icon.isNull():
            filename = 'icons/qutebrowser-64x64.png'
            icon = QImage.fromData(resources.read_file_binary(filename))

        key = self._quirks.icon_key or "image-data"
        data = self._convert_image(icon)
        if data is not None:
            hints[key] = data

        return hints
Beispiel #36
0
    def update_item_info(self, name, data):
        merged = {}
        defaults = self.assets.items().get_item(name)
        if defaults is not None:
            merged.update(defaults[0])
        merged.update(data)

        item_info = "<html><body>"
        item_info += generate_item_info(merged)
        item_info += "</body></html>"
        self.ui.desc.setText(item_info)

        inv_icon = self.assets.items().get_item_icon(name)
        image = self.assets.items().get_item_image(name)

        if inv_icon is not None:
            inv_icon = self.assets.images().color_image(inv_icon, data)
            icon = QPixmap.fromImage(ImageQt(inv_icon))
        elif image is not None:
            image = self.assets.images().color_image(image, data)
            icon = QPixmap.fromImage(ImageQt(image))
        else:
            logging.warning("Unable to load image for %s", name)
            icon = QPixmap.fromImage(QImage.fromData(self.assets.items().missing_icon()))

        icon = self.scale_image_icon(icon, 64, 64)
        self.ui.icon.setPixmap(icon)
Beispiel #37
0
    def _dataIcon(self, obj, qidx):
        if qidx.column() != 0:
            return QVariant()

        var = try_get_thumbnail(obj)
        if var:
            return var

        try:
            thumbnail = obj.thumbnail
        except AttributeError:
            return QVariant()
        if thumbnail is NotLoaded:
            self.fillObj(obj, ['thumbnail'], qidx)
        elif thumbnail is NotAvailable:
            return QVariant()
        elif thumbnail.data is NotLoaded:
            self.fillObj(thumbnail, ['data'], qidx)
        elif thumbnail.data is NotAvailable:
            return QVariant()
        else:
            img = QImage.fromData(thumbnail.data)
            store_thumbnail(obj)
            return QVariant(QIcon(QPixmap(img)))

        return QVariant()
Beispiel #38
0
    def display_photo(self):
        if self.displayed_photo_idx >= len(self.contact.photos) or self.displayed_photo_idx < 0:
            self.displayed_photo_idx = len(self.contact.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photoUrlLabel.setText('')
            return

        photo = self.contact.photos.values()[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob, lambda p: self.display_photo())
            self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.contact.backend)

            if photo.thumbnail_data:
                data = photo.thumbnail_data
            else:
                return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width()/3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '<a href="%s">%s</a>' % (photo.url, photo.url)
            if photo.hidden:
                text += '<br /><font color=#ff0000><i>(Hidden photo)</i></font>'
            self.ui.photoUrlLabel.setText(text)
Beispiel #39
0
    def _dataChanged(self, qidx):
        if qidx == self.current:
            obj = qidx.data(ResultModel.RoleObject)

            if obj.data:
                self.pixmap = QPixmap(QImage.fromData(obj.data))
            else:
                self.pixmap = QPixmap()
            self._rebuildImage()
Beispiel #40
0
def inv_icon(item_name):
    """Return a QPixmap object of the inventory icon of a given item (if possible)."""
    assets_db_file = Config().read("assets_db")
    starbound_folder = Config().read("starbound_folder")
    db = assets.Assets(assets_db_file, starbound_folder)
    icon_file = db.items().get_item_icon(item_name)

    if icon_file == None:
        try:
            image_file = db.items().get_item_image(item_name)
            return QPixmap.fromImage(ImageQt(image_file)).scaledToHeight(64)
        except (TypeError, AttributeError):
            return QPixmap.fromImage(QImage.fromData(db.items().missing_icon())).scaled(32, 32)

    try:
        return QPixmap.fromImage(ImageQt(icon_file)).scaled(32, 32)
    except AttributeError:
        return QPixmap.fromImage(QImage.fromData(db.items().missing_icon())).scaled(32, 32)
Beispiel #41
0
    def gotThumbnail(self):
        try:
            url = self.recipe.picture.url
        except AttributeError:
            return

        if not empty(url):
            data = requests.get(url).content
            img = QImage.fromData(data)
            self.ui.imageLabel.setPixmap(QPixmap.fromImage(img).scaledToWidth(250, Qt.SmoothTransformation))
Beispiel #42
0
def load_qimg(obj, *attrs):
    try:
        for attr in attrs:
            obj = getattr(obj, attr)
    except AttributeError:
        return QImage()
    if not obj:
        return QImage()

    return QImage.fromData(obj)
Beispiel #43
0
    def update_item_view(self):
        """Update item details view with data from currently selected item."""
        try:
            selected = self.ui.items.selectedItems()[0].name
        except IndexError:
            return

        try:
            item = self.items.get_item(selected)
        except TypeError:
            logging.warning("Unable to load asset "+selected)
            return

        image_file = self.items.get_item_image(selected)
        if image_file == None:
            inv_icon_file = self.items.get_item_icon(selected)
            if inv_icon_file != None:
                icon = QPixmap.fromImage(ImageQt(inv_icon_file)).scaled(32, 32)
            else:
                icon = QPixmap.fromImage(QImage.fromData(self.items.missing_icon())).scaled(32, 32)
        else:
            icon = QPixmap.fromImage(ImageQt(image_file)).scaledToHeight(64)

        # last ditch
        try:
            self.ui.item_icon.setPixmap(icon)
        except TypeError:
            logging.warning("Unable to load item image: "+selected)
            self.ui.item_icon.setPixmap(QPixmap())

        # TODO: update qt objectnames, already not making sense
        try:
            self.ui.item_name.setText(item[0]["shortdescription"])
        except KeyError:
            self.ui.item_name.setText("Missing short description")

        try:
            self.ui.short_desc.setText(item[0]["description"])
        except KeyError:
            self.ui.short_desc.setText("Missing description")

        # populate default variant table
        row = 0
        self.ui.info.setRowCount(len(item[0]))
        for key in sorted(item[0].keys()):
            try:
                text = str(key) + ": " + str(item[0][key])
                table_item = QTableWidgetItem(text)
                table_item.setToolTip(text)
                self.ui.info.setItem(row, 0, table_item)
            except TypeError:
                pass
            row += 1

        self.item_browse_select = selected
Beispiel #44
0
    def createContent(self):
        # Create the items.
        self.heading = HeadingItem(self.name, self)
        self.description = DemoTextItem(self.loadDescription(), Colors.contentFont(), Colors.heading, 500, self)
        imgHeight = 340 - int(self.description.boundingRect().height()) + 50
        self.screenshot = ImageItem(QImage.fromData(self._menu_manager.getImage(self.name)), 550, imgHeight, self)

        # Place the items on screen.
        self.heading.setPos(0, 3)
        self.description.setPos(0, self.heading.pos().y() + self.heading.boundingRect().height() + 10)
        self.screenshot.setPos(0, self.description.pos().y() + self.description.boundingRect().height() + 10)
Beispiel #45
0
def test_scales_image_to_specified_size_preserving_image_attributes():
    original_image = image_file(resources.path("front-cover.jpg"))
    scaled_image = imager.scale(original_image, 50, 50)

    assert_that(scaled_image, image_with(data=not_(empty()),
                                         mime=original_image.mime,
                                         type=original_image.type,
                                         desc=original_image.desc), "scaled image")

    picture = QImage.fromData(scaled_image.data, imager.format_for(original_image.mime))
    assert_that(picture.width(), equal_to(50), "width")
    assert_that(picture.height(), equal_to(50), "height")
Beispiel #46
0
def scale(image, width, height):
    edited = QImage.fromData(image.data, format_for(image.mime))
    if edited.isNull():
        return image

    scaled = edited.scaled(width, height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    buffer = QBuffer()
    buffer.open(QIODevice.WriteOnly)
    scaled.save(buffer, format_for(image.mime))
    buffer.close()
    return Image(mime=image.mime, data=buffer.data(), desc=image.desc, type_=image.type)
    def loadImage(self):
        image = QImage.fromData(self._parent.pages[self._parent.currentPageInd],"PNG")

        self.imageLabel.setPixmap(QPixmap.fromImage(image))
        self.fitToWindowAct.setEnabled(True)
        self.updateActions()

        if not self.fitToWindowAct.isChecked():
            self.imageLabel.adjustSize()

        self.setWindowFilePath(self._parent.fileName)
        return True
Beispiel #48
0
    def update_item_view(self):
        """Update item details view with data from currently selected item."""
        try:
            selected = self.ui.items.selectedItems()[0].name
        except IndexError:
            return

        try:
            item = self.items.get_item(selected)
        except TypeError:
            logging.warning("Unable to load asset "+selected)
            return

        inv_icon_file = self.items.get_item_icon(selected)
        if inv_icon_file is not None:
            icon = QPixmap.fromImage(ImageQt(inv_icon_file))
        else:
            image_file = self.items.get_item_image(selected)
            if image_file is not None:
                icon = QPixmap.fromImage(ImageQt(image_file))
            else:
                icon = QPixmap.fromImage(QImage.fromData(self.assets.items().missing_icon()))

        # last ditch
        try:
            icon = self.scale_image_icon(icon, 64, 64)
            self.ui.item_icon.setPixmap(icon)
        except TypeError:
            logging.warning("Unable to load item image: "+selected)
            self.ui.item_icon.setPixmap(QPixmap())

        self.ui.short_desc.setText(generate_item_info(item[0]))

        # populate default variant table

        try:
            row = 0
            self.ui.info.setRowCount(len(item[0]))
            for key in sorted(item[0].keys()):
                text = str(key) + ": " + str(item[0][key])
                table_item = QTableWidgetItem(text)
                table_item.setToolTip(text)
                self.ui.info.setItem(row, 0, table_item)
                row += 1
        except TypeError:
            self.ui.info.setRowCount(0)
            logging.error("No item data")

        self.item_browse_select = selected
Beispiel #49
0
    def updateImage(self):
        self.updatePos()
        self.updateNavButtons()

        obj = self.current.data(ResultModel.RoleObject)

        if obj.data is NotLoaded:
            self.model.fillObj(obj, ['data'], QModelIndex(self.current))
            self.pixmap = None
        elif obj.data:
            self.pixmap = QPixmap(QImage.fromData(obj.data))
        else:
            self.pixmap = QPixmap()

        self._rebuildImage()
Beispiel #50
0
def inv_icon(item_name, item_data, assets):
    """Return a QPixmap object of the inventory icon of a given item (if possible)."""
    missing = QPixmap.fromImage(QImage.fromData(assets.items().missing_icon())).scaled(32, 32)
    icon = assets.items().get_item_icon(item_name)

    if icon is None:
        # try image key instead
        image = assets.items().get_item_image(item_name)
        if image is not None:
            image = assets.images().color_image(image, item_data)
            return QPixmap.fromImage(ImageQt(image)).scaled(32, 32)
    else:
        icon = assets.images().color_image(icon, item_data)
        return QPixmap.fromImage(ImageQt(icon)).scaled(32, 32)

    return missing
 def save(self, fileName, selectedFilter):
     if selectedFilter == self.filters[1]:
         img = self.page().mainFrame().evaluateJavaScript("chart.getImageURI()")
         if img:
             ba = QByteArray()
             ba.append(img[22:])
             by = QByteArray.fromBase64(ba)
             image = QImage.fromData(by, "PNG")
             image.save(fileName)
         else:
             QMessageBox.warning(self.parent(),
                         self.tr("Saving"),
                         self.tr("Image not ready. Please try again later"))
     else:
         if selectedFilter == self.filters[0]:
             with open(fileName, 'wb') as f:
                 f.write(bytes(self.html_data, 'utf-8'))
Beispiel #52
0
    def maybe_get_icon(self):
        u"""
        Get icon for the site as a QImage if we haven’t already.

        Get the site icon, either the 'rel="icon"' or the favicon, for
        the web page at url or passed in as page_html and store it as
        a QImage. This function can be called repeatedly and loads the
        icon only once.
        """
        if self.site_icon:
            return
        if not with_pyqt:
            self.site_icon = None
            return
        page_request = urllib.request.Request(self.icon_url)
        if self.user_agent:
            page_request.add_header('User-agent', self.user_agent)
        page_response = urllib.request.urlopen(page_request)
        if 200 != page_response.code:
            self.get_favicon()
            return
        page_soup = soup(page_response, 'html.parser')
        try:
            icon_url = page_soup.find(
                name='link', attrs={'rel': 'icon'})['href']
        except (TypeError, KeyError):
            self.get_favicon()
            return
        # The url may be absolute or relative.
        if not urllib.parse.urlsplit(icon_url).netloc:
            icon_url = urllib.parse.urljoin(
                self.url, urllib.parse.quote(icon_url.encode('utf-8')))
        icon_request = urllib.request.Request(icon_url)
        if self.user_agent:
            icon_request.add_header('User-agent', self.user_agent)
        icon_response = urllib.request.urlopen(icon_request)
        if 200 != icon_response.code:
            self.site_icon = None
            return
        self.site_icon = QImage.fromData(icon_response.read())
        max_size = QSize(self.max_icon_size, self.max_icon_size)
        icon_size = self.site_icon.size()
        if icon_size.width() > max_size.width() \
                or icon_size.height() > max_size.height():
            self.site_icon = self.site_icon.scaled(
                max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
Beispiel #53
0
 def __getitem__(key):
    if key not in IconCache.icons:
       if not key.endswith('.svg') and not key.endswith('.svgz'):
          image = QImage(key).scaled(24, 24)
       else:
          svg = QSvgRenderer(key)
          image = QImage(24, 24, QImage.Format_ARGB32)
          image.fill(0)
          painter = QPainter(image)
          svg.render(painter)
          painter.end()
       bytes = QByteArray()
       buff = QBuffer(bytes)
       buff.open(QIODevice.WriteOnly)
       image.save(buff, 'png')
       IconCache.icons[key] = bytes
    return QIcon(QPixmap.fromImage(QImage.fromData(IconCache.icons[key])))
Beispiel #54
0
 def maybe_get_icon(self):
     if self.site_icon:
         return
     if not with_pyqt:
         self.site_icon = None
         return
     try:
         icon_data = self.get_data_from_url(self.full_icon_url)
     except:
         AudioDownloader.maybe_get_icon(self)
     else:
         self.site_icon = QImage.fromData(icon_data)
         max_size = QSize(self.max_icon_size, self.max_icon_size)
         ico_size = self.site_icon.size()
         if ico_size.width() > max_size.width() \
                 or ico_size.height() > max_size.height():
             self.site_icon = self.site_icon.scaled(
                 max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
def loadImage(fileName, pageNo, x, y, width, height):

    areaSelector = PDFAreaSelector(fileName)
    areaSelector.open(interactive=False)
    i = 0
    timer = QTimer()
    while len(areaSelector.pages) == 0 and i < 120:
        i += 1
        timer.start(500)
        
    image = QImage.fromData(areaSelector.pages[pageNo-1],"PNG")
    pixmap = QPixmap.fromImage(image)

    pixmapSize = pixmap.size()
    widthImg  = pixmapSize.width()
    heightImg = pixmapSize.height()

    rect = QRect(x*widthImg, y*heightImg, width*widthImg, height*heightImg)
    return pixmap.copy(rect)
Beispiel #56
0
 def render_graph(self):
     """
     build graph from data and labels
     :return:
     """
     if self.tw.data.shape[0] == 0 or self.tw.data.shape[0] != self.tw.data.shape[1]:
         return
     self.graph = Digraph(comment='Когнитивна карта', name='Cognitive map', format='png')
     for i, label in enumerate(self.tw.labels):
         self.graph.node(str(i), label, color='blue')
     size = len(self.tw.labels)
     for i in range(size):
         for j in range(size):
             weight = self.tw.data[i, j]
             if weight != 0:
                 self.graph.edge(str(i), str(j), label=str(weight),
                                 color='green' if weight > 0 else 'red')
     graph = QImage.fromData(self.graph.pipe(), "png")
     self.ui.graphView.setPixmap(QPixmap.fromImage(graph))
Beispiel #57
0
    def get_flag_icon(self):
        """
        Set self.site_icon to the right icon.

        We should use different icons, depending on the request
        language.  We store these icons in self.site_icon_dict and use the
        AudioDownloader.maybe_get_icon() if we don't have it yet.
        """
        if not with_pyqt:
            return
        try:
            # If this works we already have it.
            self.site_icon = self.site_icon_dict[self.language]
        except KeyError:
            # We have to get it ourself. (We know it's just 16x16, so
            # no resize. And we know the address).
            self.site_icon_dict[self.language] = \
                QImage.fromData(self.get_data_from_url(
                    self.icon_url_dict[self.language]))
            self.site_icon = self.site_icon_dict[self.language]
Beispiel #58
0
    def setPhoto(self, contact, item):
        if not contact:
            return False

        try:
            self.photo_processes.pop(contact.id, None)
        except KeyError:
            pass

        img = None
        for photo in contact.photos.itervalues():
            if photo.thumbnail_data:
                img = QImage.fromData(photo.thumbnail_data)
                break

        if img:
            item.setIcon(QIcon(QPixmap.fromImage(img)))
            return True

        return False