Пример #1
0
 def _plat_get_dimensions(self):
     try:
         ir = QImageReader(str(self.path))
         size = ir.size()
         if size.isValid():
             return (size.width(), size.height())
         else:
             return (0, 0)
     except EnvironmentError:
         logging.warning("Could not read image '%s'", str(self.path))
         return (0, 0)
Пример #2
0
 def _plat_get_dimensions(self):
     try:
         ir = QImageReader(str(self.path))
         size = ir.size()
         if size.isValid():
             return (size.width(), size.height())
         else:
             return (0, 0)
     except EnvironmentError:
         logging.warning("Could not read image '%s'", str(self.path))
         return (0, 0)
Пример #3
0
  def saveTiles(self):
    if self.tiles is None:
      QMessageBox.warning(None, self.plugin.pluginName, self.tr("No tiles have been downloaded."))
      return

    # Let the user choose the directory to save to
    directory = QFileDialog.getExistingDirectory(caption=self.tr("{}: Choose directory").format(self.layerDef.title))
    if not directory:
      # User cancelled the directory selection
      return

    # Build the content of the .aux.xml file containing the projection info
    projection_string = (self.crs().toWkt())
    pam_string = '<PAMDataset>\n' + \
                 '<SRS>{}</SRS>\n'.format(projection_string) + \
                 '</PAMDataset>'

    for tile in self.tiles.tiles.values():
      # Figure out the file format extension
      reader = QImageReader()
      buffer = QBuffer()
      buffer.setData(tile.data)
      buffer.open(QIODevice.ReadOnly)
      extension = str(reader.imageFormat(buffer))

      # Build the file name of the image file
      image_file_name = "{}-{}-{}.{}".format(tile.x, tile.y, tile.zoom, extension)
      image_file_path = join(directory, image_file_name)

      # Save the image file
      with open(image_file_path, 'wb') as image_file:
        image_file.write(tile.data)

      # Save the .aux.xml
      with open(image_file_path + '.aux.xml', 'w') as aux_file:
        aux_file.write(pam_string)

      # Save the world file containing the georeferencing information
      tile_rect = self.tiles.serviceInfo.getTileRect(tile.zoom, tile.x, tile.y)
      tile_size = self.tiles.TILE_SIZE
      with open(image_file_path + 'w', 'w') as world_file:
        world_file.writelines([
          str(tile_rect.width() / tile_size) + '\n',
          '0\n',
          '0\n',
          str(-tile_rect.height() / tile_size) + '\n',
          str(tile_rect.xMinimum()) + '\n',
          str(tile_rect.yMaximum()) + '\n'
        ])

    # Done
    msg = self.tr("Tiles have been saved.")
    self.showMessageBar(msg, QgsMessageBar.INFO, 2)
Пример #4
0
    def returnAvatar(self, reply):
        imageReader = QImageReader(reply)
        image = imageReader.read()

        lbl = self.ui.avatarLB
        if reply.error() == QNetworkReply.NoError:
            pixMap = QPixmap.fromImage(image).scaled(lbl.size(), Qt.KeepAspectRatio)
            lbl.setPixmap(pixMap)
            lbl.show()
        else:
            # TODO Put default image if not load from URL.
            pass
Пример #5
0
    def returnAvatar(self, reply):
        imageReader = QImageReader(reply)
        self.avatarImage = imageReader.read()

        lbl = self.avatarLB
        if reply.error() == QNetworkReply.NoError:
            pixMap = QPixmap.fromImage(self.avatarImage).scaled(lbl.size(), Qt.KeepAspectRatio)
            lbl.setPixmap(pixMap)
            lbl.show()
        else:
            # TODO Put default image if not load from URL.
            pass

        self.nameLB.setText("<html><head/><body><p><span style=\" text-decoration: underline; color:#00557f;\">" + self.currentUser + "</span></p></body></html>")
Пример #6
0
def string_handler(key, value, **kwargs):
    def parse_links():
        strings = value.split(',')
        pairs = [tuple(parts.split('|')) for parts in strings]
        handlers = []
        for pair in pairs:
            url = pair[0]
            if not any(url.startswith(proto) for proto in ['http:', 'file:']):
                continue
            try:
                name = pair[1]
            except IndexError:
                name = url
            handlers.append('<a href="{}">{}</a>'.format(url, name))
        if handlers:
            return ','.join(handlers)

    def try_image(value):
        _, extension = os.path.splitext(value)
        if extension[1:].lower() in supportedformats:
            if not os.path.exists(value):
                value = os.path.join(kwargs.get('imagepath', ''), value)
            return image_handler(key, value, imagetype='file')

        base64 = QByteArray.fromBase64(value)
        image = QPixmap()
        loaded = image.loadFromData(base64)
        if loaded:
            return image_handler(key, base64, imagetype='base64')

    global supportedformats
    if not supportedformats:
        supportedformats = [f.data() for f in QImageReader.supportedImageFormats()]

    return parse_links() or try_image(value) or value
Пример #7
0
    def returnAvatar(self, reply):
        imageReader = QImageReader(reply)
        self.avatarImage = imageReader.read()

        lbl = self.avatarLB
        if reply.error() == QNetworkReply.NoError:
            pixMap = QPixmap.fromImage(self.avatarImage).scaled(
                lbl.size(), Qt.KeepAspectRatio)
            lbl.setPixmap(pixMap)
            lbl.show()
        else:
            # TODO Put default image if not load from URL.
            pass

        self.nameLB.setText(
            "<html><head/><body><p><span style=\" text-decoration: underline; color:#00557f;\">"
            + self.currentUser + "</span></p></body></html>")
Пример #8
0
def printSupportedImageFormats():
    from PyQt4.QtGui import QImageReader
    
    formats = QImageReader.supportedImageFormats()
    print "\nSupported Image Formats:"
    for f in formats:
        print "\t" + str(f)
    print "\n"
Пример #9
0
 def dump_configinfo(self):
     from qgis.core import QgsApplication, QgsProviderRegistry
     from PyQt4.QtGui import QImageReader, QImageWriter
     yield QgsProviderRegistry.instance().pluginList()
     yield QImageReader.supportedImageFormats()
     yield QImageWriter.supportedImageFormats()
     yield QgsApplication.libraryPaths()
     yield "Translation file: {}".format(self.translationFile)
Пример #10
0
 def dump_configinfo(self):
     from qgis.core import QgsApplication, QgsProviderRegistry
     from PyQt4.QtGui import QImageReader, QImageWriter
     yield QgsProviderRegistry.instance().pluginList()
     yield QImageReader.supportedImageFormats()
     yield QImageWriter.supportedImageFormats()
     yield QgsApplication.libraryPaths()
     yield "Translation file: {}".format(self.translationFile)
Пример #11
0
    def get_archive_wallpapers(self):
        """
        Generator returning the date, path and copyright info (via db lookup) of each file found in the
        archive location.

        :rtype: QDate, unicode, unicode
        """
        image_reader = QImageReader()
        regex_date_split = re.compile(r'(\d{4})(\d{2})(\d{2})')

        copyright_info = self.copyright_db.get_all_info()
        archive_folder = self.settings.archive_location
        for filename in reversed([x for x in os.listdir(archive_folder) if re_archive_file.match(x)]):
            year, month, day = map(int, regex_date_split.findall(filename)[0])
            wallpaper_date = QDate(year, month, day)
            wallpaper_copyright = copyright_info.get('{0:04d}-{1:02d}-{2:02d}'.format(year, month, day), '')
            wallpaper_filename = os.path.join(unicode(archive_folder), filename)

            image_reader.setFileName(wallpaper_filename)
            image_size = image_reader.size()
            image_size.scale(QSize(200, 125), Qt.IgnoreAspectRatio)
            image_reader.setScaledSize(image_size)
            thumbnail_image = image_reader.read()
            if thumbnail_image.isNull():
                continue
            self.lw_wallpaper_history.add_item(thumbnail_image, wallpaper_date, wallpaper_copyright,
                                               archive_path=wallpaper_filename)
            self.app.processEvents()
        self.lw_wallpaper_history.sortItems(Qt.AscendingOrder)
Пример #12
0
    def _createFilter(self):
        formats = ''
        for f in QImageReader.supportedImageFormats():
            f = unicode(f)
            if f == 'svg':
                continue
            formats += '*.{} *.{} '.format(f.lower(), f.upper())

        return self.tr('Image files (%s);;All files (*.*)' % formats[:-1])
Пример #13
0
 def initClass(cls):
     """
     Initialize class variables
     """
     if QCoreApplication.startingUp():
         raise RuntimeError("This class need to be initialized after the QtGui application")
     cls.supported_image_types = [ bytes(i).decode() for i in QImageReader.supportedImageFormats() ]
     cls.sit_re = re.compile(u"\.(%s)$" % "|".join(cls.supported_image_types), re.IGNORECASE)
     cls.initialized = True
Пример #14
0
        def on_reply_ready(reply, future):
            nonlocal n_redir
            # schedule deferred delete to ensure the reply is closed
            # otherwise we will leak file/socket descriptors
            reply.deleteLater()
            future._reply = None
            if reply.error() == QNetworkReply.OperationCanceledError:
                # The network request was cancelled
                reply.close()
                future.cancel()
                return

            if reply.error() != QNetworkReply.NoError:
                # XXX Maybe convert the error into standard
                # http and urllib exceptions.
                future.set_exception(Exception(reply.errorString()))
                reply.close()
                return

            # Handle a possible redirection
            location = reply.attribute(
                QNetworkRequest.RedirectionTargetAttribute)

            if location is not None and n_redir < 1:
                n_redir += 1
                location = reply.url().resolved(location)
                # Retry the original request with a new url.
                request = QNetworkRequest(reply.request())
                request.setUrl(location)
                newreply = self._netmanager.get(request)
                future._reply = newreply
                newreply.finished.connect(
                    partial(on_reply_ready, newreply, future))
                reply.close()
                return

            reader = QImageReader(reply)
            image = reader.read()
            reply.close()

            if image.isNull():
                future.set_exception(Exception(reader.errorString()))
            else:
                future.set_result(image)
Пример #15
0
 def fileOpen(self):
     if not self.okToContinue():
         return
     dir = (os.path.dirname(self.filename)
            if self.filename is not None else ".")
     formats = (["*.{0}".format(unicode(format).lower())
             for format in QImageReader.supportedImageFormats()])
     fname = unicode(QFileDialog.getOpenFileName(self,
             "Image Changer - Choose Image", dir,
             "Image files ({0})".format(" ".join(formats))))
     if fname:
         self.loadFile(fname)
Пример #16
0
 def on_actionOpen_File_triggered(self):
     dir = (os.path.dirname(self.filename)
            if self.filename is not None else ".")
     formats = (["*.{0}".format(unicode(format).lower())
                 for format in QImageReader.supportedImageFormats()])
     fname = unicode(QFileDialog.getOpenFileName(self,
                                                 "Image Changer - Choose Image",
                                                 dir,
                                                 "Image files ({0})".format(" ".join(formats))))
     if fname:
         self.loadFile(fname)
         self.changeTitleOriginal()
Пример #17
0
    def write(self, f):  # TODO: separated image files (not in localBrowsingMode)
        if len(self._list) == 0:
            return

        f.write(u'\n// Base64 encoded images\n')
        for index, image in enumerate(self._list):
            imageType = image[0]
            if imageType == self.IMAGE_FILE:
                image_path = image[1]

                exists = os.path.exists(image_path)
                if exists and os.path.isfile(image_path):
                    size = QImageReader(image_path).size()
                    args = (index, size.width(), size.height(),
                            gdal2threejs.base64image(image_path))
                else:
                    f.write(u"project.images[%d] = {data:null};\n" % index)

                    if exists:
                        err_msg = u"Not image file path"
                    else:
                        err_msg = u"Image file not found"
                    logMessage(u"{0}: {1}".format(err_msg, image_path))
                    continue

            elif imageType == self.MAP_IMAGE:
                width, height, extent, transp_background = image[1]
                args = (
                    index,
                    width,
                    height,
                    self.renderedImage(
                        width,
                        height,
                        extent,
                        transp_background))

            elif imageType == self.LAYER_IMAGE:
                layerids, width, height, extent, transp_background = image[1]
                args = (
                    index,
                    width,
                    height,
                    self.renderedImage(
                        width,
                        height,
                        extent,
                        transp_background,
                        layerids))

            else:  # imageType == self.CANVAS_IMAGE:
                transp_background = image[1]
                size = self.exportSettings.mapSettings.outputSize()
                args = (index, size.width(), size.height(),
                        self.mapCanvasImage(transp_background))

            f.write(
                u'project.images[%d] = {width:%d,height:%d,data:"%s"};\n' %
                args)
Пример #18
0
  def write(self, f):   #TODO: separated image files (not in localBrowsingMode)
    if len(self._list) == 0:
      return

    f.write(u'\n// Base64 encoded images\n')
    for index, image in enumerate(self._list):
      imageType = image[0]
      if imageType == self.IMAGE_FILE:
        image_path = image[1]

        exists = os.path.exists(image_path)
        if exists and os.path.isfile(image_path):
          size = QImageReader(image_path).size()
          args = (index, size.width(), size.height(), gdal2threejs.base64image(image_path))
        else:
          f.write(u"project.images[%d] = {data:null};\n" % index)

          if exists:
            err_msg = u"Not image file path"
          else:
            err_msg = u"Image file not found"
          logMessage(u"{0}: {1}".format(err_msg, image_path))
          continue

      elif imageType == self.MAP_IMAGE:
        width, height, extent, transp_background = image[1]
        args = (index, width, height, self.renderedImage(width, height, extent, transp_background))

      elif imageType == self.LAYER_IMAGE:
        layerids, width, height, extent, transp_background = image[1]
        args = (index, width, height, self.renderedImage(width, height, extent, transp_background, layerids))

      else:   #imageType == self.CANVAS_IMAGE:
        transp_background = image[1]
        size = self.context.mapSettings.outputSize()
        args = (index, size.width(), size.height(), self.mapCanvasImage(transp_background))

      f.write(u'project.images[%d] = {width:%d,height:%d,data:"%s"};\n' % args)
Пример #19
0
        def on_reply_ready(reply, future):
            nonlocal n_redir
            if reply.error() == QNetworkReply.OperationCanceledError:
                # The network request itself was canceled
                future.cancel()
                return

            if reply.error() != QNetworkReply.NoError:
                # XXX Maybe convert the error into standard
                # http and urllib exceptions.
                future.set_exception(Exception(reply.errorString()))
                return

            # Handle a possible redirection
            location = reply.attribute(
                QNetworkRequest.RedirectionTargetAttribute)

            if location is not None and n_redir < 1:
                n_redir += 1
                print(location)
                location = reply.url().resolved(location)
                # Retry the original request with a new url.
                request = QNetworkRequest(reply.request())
                request.setUrl(location)
                newreply = self._netmanager.get(request)
                future._reply = newreply
                newreply.finished.connect(
                    partial(on_reply_ready, newreply, future))
                return

            reader = QImageReader(reply)
            image = reader.read()

            if image.isNull():
                future.set_exception(Exception(reader.errorString()))
            else:
                future.set_result(image)
Пример #20
0
        def on_reply_ready(reply, future):
            nonlocal n_redir
            if reply.error() == QNetworkReply.OperationCanceledError:
                # The network request itself was canceled
                future.cancel()
                return

            if reply.error() != QNetworkReply.NoError:
                # XXX Maybe convert the error into standard
                # http and urllib exceptions.
                future.set_exception(Exception(reply.errorString()))
                return

            # Handle a possible redirection
            location = reply.attribute(
                QNetworkRequest.RedirectionTargetAttribute)

            if location is not None and n_redir < 1:
                n_redir += 1
                print(location)
                location = reply.url().resolved(location)
                # Retry the original request with a new url.
                request = QNetworkRequest(reply.request())
                request.setUrl(location)
                newreply = self._netmanager.get(request)
                future._reply = newreply
                newreply.finished.connect(
                    partial(on_reply_ready, newreply, future))
                return

            reader = QImageReader(reply)
            image = reader.read()

            if image.isNull():
                future.set_exception(Exception(reader.errorString()))
            else:
                future.set_result(image)
Пример #21
0
def string_handler(key, value):
    global supportedformats
    if not supportedformats:
        supportedformats = [f.data() for f in QImageReader.supportedImageFormats()]

    base64 = QByteArray.fromBase64(value)
    image = QPixmap()
    loaded = image.loadFromData(base64)
    if loaded:
        return image_handler(key, base64, imagetype='base64')
    _, extension = os.path.splitext(value)
    if extension[1:] in supportedformats:
        return image_handler(key, value, imagetype='file')

    return value
Пример #22
0
    def on_iconSelect_clicked(self):
        """ Signal handler for select icon button.

        @return None
        """
        item = self.editItem
        if item:
            formats = str.join(' ', ['*.%s' % str(fmt) for fmt in
                                     QImageReader.supportedImageFormats()])
            filename = QFileDialog.getOpenFileName(
                self, 'Select Symbol Icon', '', 'Images (%s)' % formats)
            if filename:
                icon = QIcon(filename)
                item.setIcon(icon)
                self.iconPreview.setPixmap(icon.pixmap(32,32))
                settings = self.settings
                settings.setValue('%s/icon' % item.symbol, icon)
                self.emit(Signals.modified)
Пример #23
0
    def __init__(self, tree_widget, controls_ui, controller, logger):
        self.tree = tree_widget
        self.controls_ui = controls_ui
        self.controller = controller
        self.datahandler = controller.datahandler
        self.logger = logger

        self.root_folder = None
        self.last_clicked = None
        self.connection = None
        self.selected_data = None
        self.current_public_link = None
        self.loading_ui = None
        
        # Treeview header init
        headers = self.tree.headerItem()
        headers.setTextAlignment(0, Qt.AlignLeft|Qt.AlignVCenter)
        headers.setTextAlignment(1, Qt.AlignRight|Qt.AlignVCenter)

        font = headers.font(0)
        font.setPointSize(12)
        headers.setFont(0, font)
        headers.setFont(1, font)
        
        self.tree.header().resizeSections(QHeaderView.ResizeToContents)
        
        # Click tracking
        self.clicked_items = {}
        
        # Supported thumb image formats
        self.supported_reader_formats = QImageReader.supportedImageFormats()
        
        # Thumbs init
        self.thumbs = {}

        # Current loading anim list
        self.load_animations = []
        
        # Connects
        self.tree.itemSelectionChanged.connect(self.item_selection_changed)
        self.tree.itemClicked.connect(self.item_clicked)
        self.tree.itemExpanded.connect(self.item_expanded)
        self.tree.itemCollapsed.connect(self.item_collapsed)
def image_meta_data(path):
    reader = QImageReader(path)
    if not reader.canRead():
        return ImgDataError(path, reader.error(), reader.errorString())

    img_format = reader.format()
    img_format = bytes(img_format).decode("ascii")
    size = reader.size()
    if not size.isValid():
        height = width = float("nan")
    else:
        height, width = size.height(), size.width()
    try:
        st_size = os.stat(path).st_size
    except OSError:
        st_size = -1

    return ImgData(path, img_format, height, width, st_size)
Пример #25
0
    def on_actionAbout_triggered(self):
        dlg = QMessageBox(self)
        dlg.setWindowTitle("About Point Tracker")
        dlg.setIconPixmap(self.windowIcon().pixmap(64, 64))
        #dlg.setTextFormat(Qt.RichText)

        dlg.setText("""Point Tracker Tool version %s rev %s
Developper: Pierre Barbier de Reuille <*****@*****.**>
Copyright 2008
""" % (__version__, __revision__))

        img_read = ", ".join(str(s) for s in QImageReader.supportedImageFormats())
        img_write = ", ".join(str(s) for s in QImageWriter.supportedImageFormats())

        dlg.setDetailedText("""Supported image formats:
  - For reading: %s

  - For writing: %s
""" % (img_read, img_write))
        dlg.exec_()
Пример #26
0
    def on_iconSelect_clicked(self):
        """ Signal handler for select icon button.

        @return None
        """
        item = self.editItem
        if item:
            formats = str.join(' ', [
                '*.%s' % str(fmt)
                for fmt in QImageReader.supportedImageFormats()
            ])
            filename = QFileDialog.getOpenFileName(self, 'Select Symbol Icon',
                                                   '', 'Images (%s)' % formats)
            if filename:
                icon = QIcon(filename)
                item.setIcon(icon)
                self.iconPreview.setPixmap(icon.pixmap(32, 32))
                settings = self.settings
                settings.setValue('%s/icon' % item.symbol, icon)
                self.emit(Signals.modified)
Пример #27
0
    def on_actionAbout_triggered(self):
        dlg = QMessageBox(self)
        dlg.setWindowTitle("About Point Tracker")
        dlg.setIconPixmap(self.windowIcon().pixmap(64, 64))
        #dlg.setTextFormat(Qt.RichText)

        dlg.setText("""Point Tracker Tool version %s rev %s
Developper: Pierre Barbier de Reuille <*****@*****.**>
Copyright 2008
""" % (__version__, __revision__))

        img_read = ", ".join(
            str(s) for s in QImageReader.supportedImageFormats())
        img_write = ", ".join(
            str(s) for s in QImageWriter.supportedImageFormats())

        dlg.setDetailedText("""Supported image formats:
  - For reading: %s

  - For writing: %s
""" % (img_read, img_write))
        dlg.exec_()
Пример #28
0
def string_handler(key, value, **kwargs):
    def parse_links():
        strings = value.split(',')
        pairs = [tuple(parts.split('|')) for parts in strings]
        handlers = []
        for pair in pairs:
            url = pair[0]
            if not any(url.startswith(proto) for proto in ['http:', 'file:']):
                continue
            try:
                name = pair[1]
            except IndexError:
                name = url
            handlers.append('<a href="{}">{}</a>'.format(url, name))
        if handlers:
            return ','.join(handlers)

    def try_image(value):
        _, extension = os.path.splitext(value)
        if extension[1:].lower() in supportedformats:
            if not os.path.exists(value):
                value = os.path.join(kwargs.get('imagepath', ''), value)
            return image_handler(key, value, imagetype='file')

        newvalue = value.encode("utf-8")
        base64 = QByteArray.fromBase64(newvalue)
        image = QPixmap()
        loaded = image.loadFromData(base64)
        if loaded:
            return image_handler(key, base64, imagetype='base64')

    global supportedformats
    if not supportedformats:
        supportedformats = [
            f.data() for f in QImageReader.supportedImageFormats()
        ]

    return parse_links() or try_image(value) or value
def image_meta_data(path):
    reader = QImageReader(path)
    if not reader.canRead():
        return ImgDataError(path, reader.error(), reader.errorString())

    img_format = reader.format()
    img_format = bytes(img_format).decode("ascii")
    size = reader.size()
    if not size.isValid():
        height = width = float("nan")
    else:
        height, width = size.height(), size.width()
    try:
        st_size = os.stat(path).st_size
    except OSError:
        st_size = -1

    return ImgData(path, img_format, height, width, st_size)
Пример #30
0
 def dump_configinfo(self):
     yield QgsProviderRegistry.instance().pluginList()
     yield QImageReader.supportedImageFormats()
     yield QImageWriter.supportedImageFormats()
     yield QgsApplication.libraryPaths()
     yield "Translation file: {}".format(self.translationFile)
Пример #31
0
import roam.utils
from roam.mainwindow import MainWindow

def excepthook(errorhandler, exctype, value, traceback):
    errorhandler(exctype, value, traceback)
    roam.utils.error("Uncaught exception", exc_info=(exctype, value, traceback))

start = time.time()
roam.utils.info("Loading Roam")

QgsApplication.setPrefixPath(prefixpath, True)
QgsApplication.initQgis()

roam.utils.info(QgsApplication.showSettings())
roam.utils.info(QgsProviderRegistry.instance().pluginList())
roam.utils.info(QImageReader.supportedImageFormats())
roam.utils.info(QImageWriter.supportedImageFormats())
roam.utils.info(QgsApplication.libraryPaths())

QApplication.setStyle("Plastique")
QApplication.setFont(QFont('Segoe UI'))

class Settings:
    def __init__(self, path):
        self.path = path
        self.settings = {}

    def load(self):
        settingspath = self.path
        with open(settingspath, 'r') as f:
            self.settings = yaml.load(f)
Пример #32
0
    def update(self):
        """ Fonction de mise à jour de la préview :
            * Si la taille de l'image est plus petite que la taille souhaité, on n'agrandi pas l'image, on prend la plus petite des deux
            * Le cache contient en index les images+size"""
        miniImg = QImage()
        image = QImageReader(self.imageName)
        self.origineSize = image.size()
        image.setQuality(self.quality)
        if not self.magnify :
            if ( ( self.size.width() + self.size.height() ) > (image.size().width() + image.size().height() ) ) :
                self.size = image.size()

        if self.keepRatio :
            image.setScaledSize(QSize(self.size.width(), image.size().height() * self.size.width() / image.size().width() ) )
        else :
            image.setScaledSize(self.size)

        if not QPixmapCache.find(self.imageName + str(self.size), self.preview) or not self.cache:
            image.read(miniImg)
            self.preview = self.preview.fromImage(miniImg)
            if self.cache :
                QPixmapCache.insert(self.imageName + str(self.size), self.preview)
def supportedImageFormats():
    return [bytes(fmt).decode("ascii")
            for fmt in QImageReader.supportedImageFormats()]
Пример #34
0
    def setupScene(self):
        self.error()
        if self.data:
            attr = self.stringAttrs[self.imageAttr]
            titleAttr = self.allAttrs[self.titleAttr]
            instances = [inst for inst in self.data
                         if numpy.isfinite(inst[attr])]
            assert self.thumbnailView.count() == 0
            size = QSizeF(self.imageSize, self.imageSize)

            for i, inst in enumerate(instances):
                url = self.urlFromValue(inst[attr])
                title = str(inst[titleAttr])

                thumbnail = GraphicsThumbnailWidget(QPixmap(), title=title)
                thumbnail.setThumbnailSize(size)
                thumbnail.setToolTip(url.toString())
                thumbnail.instance = inst
                self.thumbnailView.addThumbnail(thumbnail)

                if url.isValid() and url.isLocalFile():
                    reader = QImageReader(url.toLocalFile())
                    image = reader.read()
                    if image.isNull():
                        error = reader.errorString()
                        thumbnail.setToolTip(
                            thumbnail.toolTip() + "\n" + error)
                        self._errcount += 1
                    else:
                        pixmap = QPixmap.fromImage(image)
                        thumbnail.setPixmap(pixmap)
                        self._successcount += 1

                    future = Future()
                    future.set_result(image)
                    future._reply = None
                elif url.isValid():
                    future = self.loader.get(url)

                    @future.add_done_callback
                    def set_pixmap(future, thumb=thumbnail):
                        if future.cancelled():
                            return

                        assert future.done()

                        if future.exception():
                            # Should be some generic error image.
                            pixmap = QPixmap()
                            thumb.setToolTip(thumb.toolTip() + "\n" +
                                             str(future.exception()))
                        else:
                            pixmap = QPixmap.fromImage(future.result())

                        thumb.setPixmap(pixmap)

                        self._noteCompleted(future)
                else:
                    future = None

                self.items.append(_ImageItem(i, thumbnail, url, future))

            if any(it.future is not None and not it.future.done()
                   for it in self.items):
                self.info.setText("Retrieving...\n")
            else:
                self._updateStatus()
Пример #35
0
import os
from types import NoneType
from string import Template

from PyQt4.QtCore import QUrl, QByteArray, QDate, QDateTime, QTime
from PyQt4.QtGui import (QDialog, QWidget, QGridLayout, QPixmap,
                         QImageReader, QDesktopServices)
from PyQt4.QtWebKit import QWebView, QWebPage

from roam import utils


images = {}
formats = [f.data() for f in QImageReader.supportedImageFormats()]


def image_handler(key, value, **kwargs):
    imageblock = '''
                    <a href="{}" class="thumbnail">
                      <img width="200" height="200" src="{}"\>
                    </a>'''

    imagetype = kwargs.get('imagetype', 'base64' )
    global images
    images[key] = (value, imagetype)
    if imagetype == 'base64':
        src = 'data:image/png;base64,${}'.format(value.toBase64())
    else:
        src = value
    return imageblock.format(key, src)
def supportedImageFormats():
    return [
        bytes(fmt).decode("ascii")
        for fmt in QImageReader.supportedImageFormats()
    ]
Пример #37
0
 def load_an_image(self):
     return QImageReader("/tmp/plot.svg").read()
     return QImageReader("/tmp/strawberry.gif").read()
Пример #38
0
    'txt'   :   UTF8TextFile,
    'tar'   :   TarFileType,
    'gz'    :   ArchiveFileType,
    'bz2'   :   ArchiveFileType,
    'gzip'  :   ArchiveFileType,
    'zip'   :   ArchiveFileType,
    'xz'    :   ArchiveFileType,
    'tgz'   :   ArchiveFileType,
    'properties':   PropsFileType,
}


__cachedFileTypes = {}
__magicModule = None
__QTSupportedImageFormats = [ str( fmt ) for fmt in
                              QImageReader.supportedImageFormats() ]


def __isMagicAvailable():
    " Checks if the magic module is able to be loaded "
    try:
        import magic
        m = magic.Magic()
        m.close()
        return True
    except:
        return False

# Cached value to avoid unnecessary searches for a name
MAGIC_AVAILABLE = __isMagicAvailable()