本文整理汇总了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)
示例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)
示例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
示例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>")
示例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
示例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"
示例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)
示例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)
示例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)
示例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)
示例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)
示例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)
示例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
示例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)
示例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)