當前位置: 首頁>>代碼示例>>Python>>正文


Python QtGui.QImageReader類代碼示例

本文整理匯總了Python中PyQt4.QtGui.QImageReader的典型用法代碼示例。如果您正苦於以下問題:Python QImageReader類的具體用法?Python QImageReader怎麽用?Python QImageReader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了QImageReader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _plat_get_dimensions

 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)
開發者ID:astrofrog,項目名稱:dupeguru,代碼行數:11,代碼來源:app.py

示例2: saveTiles

  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)
開發者ID:minorua,項目名稱:TileLayerPlugin,代碼行數:53,代碼來源:tilelayer.py

示例3: returnAvatar

    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
開發者ID:gkudos,項目名稱:qgis-cartodb,代碼行數:12,代碼來源:UserData.py

示例4: returnAvatar

    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>")
開發者ID:gkudos,項目名稱:qgis-cartodb,代碼行數:14,代碼來源:CartoDBToolbar.py

示例5: string_handler

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
開發者ID:HeatherHillers,項目名稱:RoamMac,代碼行數:35,代碼來源:htmlviewer.py

示例6: printSupportedImageFormats

def printSupportedImageFormats():
    from PyQt4.QtGui import QImageReader
    
    formats = QImageReader.supportedImageFormats()
    print "\nSupported Image Formats:"
    for f in formats:
        print "\t" + str(f)
    print "\n"
開發者ID:gubatron,項目名稱:blooploader,代碼行數:8,代碼來源:__init__.py

示例7: dump_configinfo

 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)
開發者ID:Kenyat1989,項目名稱:Roam,代碼行數:8,代碼來源:environ.py

示例8: get_archive_wallpapers

    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)
開發者ID:se0siris,項目名稱:bing-wallpaper-changer,代碼行數:29,代碼來源:mainwindow.py

示例9: on_reply_ready

        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)
開發者ID:BlazZupan,項目名稱:orange3,代碼行數:44,代碼來源:owimageviewer.py

示例10: fileOpen

 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)
開發者ID:imagingearth,項目名稱:PyQt4-Examples,代碼行數:12,代碼來源:MainWindow_ans.py

示例11: write

  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)
開發者ID:Ecocline,項目名稱:Qgis2threejs,代碼行數:38,代碼來源:datamanager.py

示例12: on_reply_ready

        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)
開發者ID:Micseb,項目名稱:orange3,代碼行數:37,代碼來源:owimageviewer.py

示例13: string_handler

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
開發者ID:henriquespedro,項目名稱:Roam,代碼行數:15,代碼來源:htmlviewer.py

示例14: on_iconSelect_clicked

    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)
開發者ID:InfiniteAlpha,項目名稱:profitpy,代碼行數:18,代碼來源:main.py

示例15: __init__

    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)
開發者ID:Sohil876,項目名稱:DropN900,代碼行數:43,代碼來源:uicontroller.py


注:本文中的PyQt4.QtGui.QImageReader類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。