def __init__(self, file_path, make_opengl_textures=True): image_reader = QImageReader(file_path) self.is_animated = image_reader.supportsAnimation() if self.is_animated: self.num_frames = image_reader.imageCount() # -1 means loop infinitely, 0 means no loop, > 0 is finite # of loops self.loop_count = image_reader.loopCount() self.loops_remaining = 0 self.frames = [] self.delays = [] while image_reader.currentImageNumber() < image_reader.imageCount() - 1: self.frames.append(image_reader.read()) self.delays.append(image_reader.nextImageDelay()) if make_opengl_textures: self.open_gl_textures = [QOpenGLTexture(this_frame.mirrored()) for this_frame in self.frames] self.made_opengl_textures = True self.frames_and_delays = zip(self.frames, self.delays) self.current_frame = 0 self.animating = False else: self.image = image_reader.read() assert isinstance(self.image, QImage) if make_opengl_textures: self.open_gl_texture = QOpenGLTexture(self.image.mirrored()) self.made_opengl_textures = True
def openFile(self, filepath=False): if not filepath: filefilter = "Image files (*.jpg *.png *.jpeg *.svg *.gif *.tiff *.ppm *.bmp);;JPEG Images (*.jpg *.jpeg);;PNG Images (*.png);;SVG Images (*.svg);;All Files (*)" filepath, sel_filter = QFileDialog.getOpenFileName( self, 'Open Image', self.filepath, filefilter) if filepath == '': return image_reader = QImageReader(filepath) if image_reader.format() == 'gif': # For gif animations anim = QMovie(filepath) self.image.setAnimation(anim) self.adjustWindowSize(True) self.statusbar.showMessage( "Resolution : %ix%i" % (self.image.width(), self.image.height())) self.disableButtons(True) else: # For static images image_reader.setAutoTransform(True) pm = QPixmap.fromImageReader(image_reader) if not pm.isNull(): self.image.scale = self.getOptimumScale(pm) self.image.setImage(pm) self.adjustWindowSize() self.disableButtons(False) else: return self.filepath = filepath self.setWindowTitle(QFileInfo(filepath).fileName())
def __init__(self, original_path, duplicate_path, parent): super(ImageCompare, self).__init__(parent) layout = QHBoxLayout() img1 = QVBoxLayout() img2 = QVBoxLayout() self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle('Image Compare') original_label = QLabel('Original Image') original_label.setAlignment(Qt.AlignCenter) original = QLabel('Original Image') original.setAlignment(Qt.AlignCenter) pixel1 = QPixmap(QImageReader(original_path).read()) original.setPixmap(pixel1.scaled(500, 1000, Qt.KeepAspectRatio)) img1.addWidget(original_label) img1.addWidget(original) duplicate_label = QLabel('Duplicate Image') duplicate_label.setAlignment(Qt.AlignCenter) duplicate = QLabel('Duplicate Image') duplicate.setAlignment(Qt.AlignCenter) pixel2 = QPixmap(QImageReader(duplicate_path).read()) duplicate.setPixmap(pixel2.scaled(500, 1000, Qt.KeepAspectRatio)) img2.addWidget(duplicate_label) img2.addWidget(duplicate) layout.addLayout(img1) layout.addLayout(img2) self.setLayout(layout) self.show()
def __init__(self, path: str, file_format: str): super().__init__(path, file_format) self._handler = QImageReader(path, file_format.encode()) self._handler.setAutoTransform(True) if not self._handler.canRead(): # TODO raise ValueError(f"'{path}' cannot be read as image")
def _loadQtImage(path: str) -> QImage: reader = QImageReader(path) image = QImage(reader.read()) if not image.isNull(): return image else: return None
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue( "/Projections/defaultBehavior", "useGlobal" ) # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def run(self): self.sock.bind(('', configs['live']['port'])) self.sock.settimeout(1) print('LiveClient bind in ', self.sock.getsockname()) while not self.stop_run: while self.wait_recv: try: receive_data = self.sock.recv(1024 * 100) # , address self.wait_recv = False except: pass self.wait_recv = True if self.stop_run: break receive_data = zlib.decompress(receive_data) byte_array = QByteArray(receive_data) buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadOnly) # 读取图片 reader = QImageReader(buffer) q_img = reader.read() if self.stop_run: break self._screen.emit(q_img) self.sock.close() # 关闭套接字
def load(self, source): """Load anything that QImageReader or QMovie constructors accept""" # Use QImageReader to identify animated GIFs for separate handling # (Thanks to https://stackoverflow.com/a/20674469/435253 for this) image_reader = QImageReader(source) from PyQt5.QtGui import QImageIOHandler if image_reader.supportsAnimation() and image_reader.imageCount() > 1: movie = QMovie(source) # Calculate the aspect ratio and adjust the widget size movie.jumpToFrame(0) movie_size = movie.currentImage().size() self.movie_aspect = movie_size.width() / movie_size.height() self.resizeEvent() self.label.setMovie(movie) movie.start() # Free memory if the previous image was non-animated self.orig_pixmap = None else: self.orig_pixmap = QPixmap(image_reader.read()) self.label.setPixmap(self.orig_pixmap) # Fail quickly if our violated invariants result in stale # aspect-ratio information getting reused self.movie_aspect = None # Keep the image from preventing downscaling self.setMinimumSize(1, 1)
def image_and_format_from_data(data): ' Create an image object from the specified data which should be a bytestring and also return the format of the image ' ba = QByteArray(data) buf = QBuffer(ba) buf.open(QBuffer.ReadOnly) r = QImageReader(buf) fmt = bytes(r.format()).decode('utf-8') return r.read(), fmt
def findIconHelper(self, size = int, themeName = str, iconName = str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x:x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image=QImage(size, size, QImage.Format_RGB32) reader=QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def findIconHelper(self, size=int, themeName=str, iconName=str): pixmap = QPixmap() if iconName == '' or self.themeName == '': return pixmap if themeName == '': themeName = self.themeName if themeName == self.themeName: index = self.themeIndex else: index = self.readThemeIndex(themeName) subDirs = filter(lambda x: x[0] == str(size), index.dirList) for iconDir in self.iconDirs: if path.exists(path.join(iconDir, themeName)): for theme in subDirs: fileName = path.join(iconDir, themeName, theme[1], '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, themeName, theme[1], '%s.svg' % str(iconName)) logging.debug('Looking for : %s' % fileName) if path.exists(fileName): pixmap.load(fileName) logging.debug('Icon: %s found in theme %s' % \ (iconName, themeName)) return pixmap elif path.exists(fileName_svg): pixmap.load(fileName_svg) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap for iconDir in self.extraIcons: fileName = path.join(iconDir, '%s.png' % str(iconName)) fileName_svg = path.join(iconDir, '{}.svg'.format(str(iconName))) if path.exists(fileName): pixmap.load(fileName) #print "pixmap ->{}".format(fileName) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) return pixmap elif path.exists(fileName_svg): image = QImage(size, size, QImage.Format_RGB32) reader = QImageReader(fileName) reader.read(image) pixmap.convertFromImage(image) logging.debug('Icon: %s found in %s' % (iconName, iconDir)) #print "pixmap ->{}".format(fileName) return pixmap if len(self._themes) > 0: self._themes.pop(0) if not len(self._themes) == 0 and pixmap.isNull(): pixmap = self.findIconHelper(size, self._themes[0], iconName) return pixmap
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True filepath = self.getAbsoluteFilepath() if not os.path.exists(filepath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(filepath) result = loadErrorDialog.exec_() if result == 1: # absolute filepath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(filepath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog reader = QImageReader(filepath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(filepath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def inv_icon(item_name): """Return a QPixmap object of the inventory icon of a given item (if possible).""" icon_file = assets.Items().get_item_icon(item_name) if icon_file == None: return QPixmap() reader = QImageReader(icon_file[0]) reader.setClipRect(QtCore.QRect(icon_file[1], 0, 16, 16)) return QPixmap.fromImageReader(reader).scaled(32, 32)
def preview_icon(race, gender): """Return an icon image for player race/gender previews.""" icon_file = assets.Player().get_preview_icon(race, gender) if icon_file == None: return QPixmap() reader = QImageReader(icon_file) reader.setClipRect(QtCore.QRect(0, 0, 32, 32)) return QPixmap.fromImageReader(reader)
class QtReader(BaseReader): """Image reader using Qt's QImageReader implementation under the hood.""" def __init__(self, path: str, file_format: str): super().__init__(path, file_format) self._handler = QImageReader(path, file_format.encode()) self._handler.setAutoTransform(True) if not self._handler.canRead(): # TODO raise ValueError(f"'{path}' cannot be read as image") @classmethod def supports(cls, file_format: str) -> bool: return file_format in QImageReader.supportedImageFormats() @property def is_animation(self) -> bool: return self._handler.supportsAnimation() def get_pixmap(self) -> QPixmap: """Retrieve the pixmap directly from the image reader.""" pixmap = QPixmap.fromImageReader(self._handler) if self._handler.error(): raise ValueError( f"Error reading image '{self.path}': {self._handler.errorString()}" ) return pixmap def get_image(self, size: int) -> QImage: """Retrieve the down-scaled image directly from the image reader.""" qsize = self._handler.size() qsize.scale(size, size, Qt.KeepAspectRatio) self._handler.setScaledSize(qsize) return self._handler.read()
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)
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def addPhoto(self): filefilter = "JPEG Images (*.jpg *jpeg);;PNG Images (*.png);;All Files (*)" filepath, sel_filter = QFileDialog.getOpenFileName(self, 'Open Image', '', filefilter) if filepath == '' : return image_reader = QImageReader(filepath) image_reader.setAutoTransform(True) pm = QPixmap.fromImageReader(image_reader) if not pm.isNull() : thumbnail = Thumbnail(pm, self.frame) self.verticalLayout.addWidget(thumbnail) thumbnail.clicked.connect(self.gridPaper.setPhoto) self.thumbnailGr.append(thumbnail)
def _can_write(self): """Check if it is possible to save the current path. Raises: WriteError if writing is not possible. """ if not isinstance(self._pixmap, QPixmap): raise WriteError("Cannot write animations") if os.path.exists(self._path): # Override current path reader = QImageReader(self._path) if not reader.canRead(): raise WriteError("Path '%s' exists and is not an image" % (self._path))
def __display_result_image(self, file_path): image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.resultView.height() widget_width = self.resultView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.resultView.setScene(scene) else: scene = QGraphicsScene() self.resultView.setScene(scene)
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 reader0 = QImageReader(imagePath) reader0.setAutoTransform(True) image = reader0.read() 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']) direction = shape['direction'] isRotated = shape['isRotated'] extra_text = shape['extra_text'] if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult, extra_text) else: #if shape is rotated box, save as rotated bounding box robndbox = LabelFile.convertPoints2RotatedBndBox(shape) writer.addRotatedBndBox(robndbox[0], robndbox[1], robndbox[2], robndbox[3], robndbox[4], label, difficult, extra_text) writer.save(targetFile=filename) return
def _can_write(pixmap, path): """Check if it is possible to save the current path. See write_pixmap for the args description. Raises: WriteError if writing is not possible. """ if not isinstance(pixmap, QPixmap): raise WriteError("Cannot write animations") if os.path.exists(path): # Override current path reader = QImageReader(path) if not reader.canRead(): raise WriteError(f"Path '{path}' exists and is not an image")
def load_and_unpickle_image_hash(self, filepath): image_hash = {} bytearray_hash = pickle.load(open(filepath, "rb")) for k in bytearray_hash.keys(): byte_array = bytearray_hash[k] buffer = QBuffer(byte_array) buffer.open(QIODevice.ReadOnly) reader = QImageReader(buffer) img = reader.read() image_hash[k] = img return image_hash
def prep_image(self): """ Prepare the image to be displayed on screen. """ QImageReader.supportedImageFormats() self.original = image_tools.prepare_image(self.path, self) self.display_properties() self.to_display = self.original.copy() self.before_filter = self.original.copy() self.cache_colors = image_tools.get_modes(self.original) self.original_alpha = self.original.getchannel("A").copy() self.qt_tweaks() self.adjust_size() self.set_pixmap()
def __changed_image_line_edit(self): file_path = self.lineEdit_image.text() image_reader = QImageReader(file_path) if image_reader.canRead() is True: widget_height = self.queryView.height() widget_width = self.queryView.width() image = image_reader.read().scaled(widget_width, widget_height, Qt.KeepAspectRatio) item = QGraphicsPixmapItem(QPixmap.fromImage(image)) scene = QGraphicsScene() scene.addItem(item) self.queryView.setScene(scene) else: scene = QGraphicsScene() self.queryView.setScene(scene)
def accept(self): for key, field in self.fields.items(): self.data[key] = field["edit"].text() if self.data["name"] == "": msgBox = QMessageBox() msgBox.setText("Please, enter a name for the map.") msgBox.exec() return # check if the RGB map file exists rgb_filename = self.data['rgb_filename'] if not os.path.exists(rgb_filename): msgBox = QMessageBox() msgBox.setText("The RGB image file does not seems to exist.") msgBox.exec() return # check if the depth map file exists depth_filename = self.data['depth_filename'] if not os.path.exists(rgb_filename): msgBox = QMessageBox() msgBox.setText("The depth map file does not seems to exist.") msgBox.exec() return # check validity of the acquisition date txt = self.data["acquisition_date"] if not utils.isValidDate(txt): msgBox = QMessageBox() msgBox.setText( "Invalid date format. Please, enter the acquisition date as YYYY-MM-DD." ) msgBox.exec() return # TODO: redundat check, remove it ? image_reader = QImageReader(rgb_filename) size = image_reader.size() if size.width() > 32767 or size.height() > 32767: msgBox = QMessageBox() msgBox.setText( "The image is too big. TagLab is limited to 32767x32767 pixels." ) msgBox.exec() return self.accepted.emit() self.close()
def __init__(self, parent, files: [], dest_album: AlbumData): super().__init__(parent) self.setWindowFlag(Qt.WindowCloseButtonHint, False) self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.setWindowTitle('Album Content Importer') self.setWindowIcon(QIcon(QPixmap(QImageReader('assets/importAlbumContent.png').read()))) # Layout setup layout = QVBoxLayout() layout.addWidget(QLabel('Importing new files...')) self.progress = QProgressBar() self.progress.setValue(0) self.progress.setFormat('Waiting (%p%)') layout.addWidget(self.progress) self.current_file = QLabel('Waiting...') layout.addWidget(self.current_file) layout.addStretch() # Init thread self.progress_signal.connect(self.update_progress) self.thread_pool = QThreadPool() self.thread_worker = Worker(self.run) self.thread_worker.signals.progress.connect(self.progress_signal) self.thread_worker.signals.finished.connect(self.update_after_completion) self.files = files self.dest_album = dest_album self.setLayout(layout) self.setFixedSize(300, 80) self.thread_pool.start(self.thread_worker) self.exec()
def get(self, name, ext='*'): for file in os.listdir(self._path): if ext == '*' or file.endswith(ext): imageReader = QImageReader(file) if imageReader: return QPixmap.fromImageReader(imageReader) return os.path.join(self._path, file) return None
def inv_icon(item_name): """Return an ItemWidget with icon from item name.""" icon_file = assets.Items().get_item_icon(item_name) if icon_file == None: return None if icon_file[1] == "chest": offset = 16 elif icon_file[1] == "pants": offset = 32 else: offset = 0 reader = QImageReader(icon_file[0]) reader.setClipRect(QtCore.QRect(offset, 0, 16, 16)) return QPixmap.fromImageReader(reader).scaled(32, 32)
def __init__(self, *__args): if not self.supported_image_formats: self.supported_image_formats = [ f.data().decode('utf-8') for f in QImageReader.supportedImageFormats() ] super().__init__(*__args)
def imageNameFilters(): result = [] mimeDatabase = QMimeDatabase() supportedMimeTypes = QImageReader.supportedMimeTypes() for m in supportedMimeTypes: suffixes = mimeDatabase.mimeTypeForName(m.data().decode()).suffixes() for suffix in suffixes: result.append(f"*.{suffix}") return result
def fileOpen(self): if not self.okToContinue(): return dir = os.path.dirname(self.filename) if self.filename is not None else '.' formats = ['{0}'.format(str(format).lower()) for format in QImageReader.supportedImageFormats()] formats = ['*.{0}'.format(format[2:5]) for format in formats] fname,_ = QFileDialog.getOpenFileName(self, 'Image Editor - Choose Image', dir, 'Image File ({0})'.format(" ".join(formats))) if fname: self.loadFile(fname)
def test(h: bytes, f: BinaryIO) -> Optional[str]: if check(h, f): if hasattr(test, "checked"): return name if name in QImageReader.supportedImageFormats(): setattr(test, "checked", True) return name imghdr.tests.remove(test) return None
def __init__(self, parent, album_list, edit: bool = False, current_album: AlbumData = None, prefill_title: str = '', prefill_desc: str = ''): super().__init__(parent) self.setMinimumWidth(300) self.setWindowFlag(Qt.WindowContextHelpButtonHint, False) self.album_list = album_list self.edit = edit buttons = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.button_box = QDialogButtonBox(buttons) self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) self.button_box.rejected.connect(self.my_reject) self.button_box.accepted.connect(self.accept) layout = QVBoxLayout() self.setLayout(layout) t_label = QLabel('Title (Required)') self.title = QLineEdit() self.title.setText(prefill_title) self.title.textChanged.connect(self.check_text) d_label = QLabel('Description') self.description = QLineEdit() self.description.setText(prefill_desc) layout.addWidget(t_label) layout.addWidget(self.title) layout.addWidget(d_label) layout.addWidget(self.description) layout.addStretch() layout.addWidget(self.button_box) if edit: self.setWindowTitle('Album Edit Tool') self.setWindowIcon(QIcon(QPixmap(QImageReader('assets/editAlbum.png').read()))) self.title.setText(current_album.get_title()) self.description.setText(current_album.get_description()) else: self.setWindowIcon(QIcon(QPixmap(QImageReader('assets/newAlbum.png').read()))) self.setWindowTitle('Album Creation Tool') if len(prefill_title) > 0: self.check_text() self.exec()
def dragEnterEvent(self, event): mimeData = event.mimeData() if mimeData.hasUrls(): paths = mimeData.urls() path = paths[0].toLocalFile() ext = os.path.splitext(path)[1][1:] if ext.lower() in QImageReader.supportedImageFormats(): event.acceptProposedAction() else: super().dragEnterEvent(event)
def replaceImage(self, filepath, title): self.title = title self.filepath = filepath # set custom properties self.setCustomProperty("title", title) self.setCustomProperty("filepath", self.filepath) self.setName(title) fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(), layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.repaint()
def showPreviewDialog(self): """ Show images preview dialog """ if self.previewDialog is None: #Create window if not exists self.previewDialog = DiviPluginPreviewDialog(self) model = self.tvIdentificationResult.model().sourceModel() item = model.findItem('attachments') image_items = [] supportedFormats = QImageReader.supportedImageFormats() #Filter attachments by extension of supported formats for itm in item.childItems: ext = op.splitext(itm.name)[-1][1:].lower() if ext in supportedFormats: image_items.append( itm ) fid = self.tvIdentificationResult.model().sourceModel().currentFeature self.previewDialog.show(fid, image_items)
def test_qt(self): from PyQt5.QtGui import QImageReader, QFontDatabase from PyQt5.QtNetwork import QNetworkAccessManager from calibre.utils.img import image_from_data, image_to_data, test # Ensure that images can be read before QApplication is constructed. # Note that this requires QCoreApplication.libraryPaths() to return the # path to the Qt plugins which it always does in the frozen build, # because the QT_PLUGIN_PATH env var is set. On non-frozen builds, # it should just work because the hard-coded paths of the Qt # installation should work. If they do not, then it is a distro # problem. fmts = set(map(lambda x: x.data().decode('utf-8'), QImageReader.supportedImageFormats())) # no2to3 testf = {'jpg', 'png', 'svg', 'ico', 'gif'} self.assertEqual(testf.intersection(fmts), testf, "Qt doesn't seem to be able to load some of its image plugins. Available plugins: %s" % fmts) data = P('images/blank.png', allow_user_override=False, data=True) img = image_from_data(data) image_from_data(P('catalog/mastheadImage.gif', allow_user_override=False, data=True)) for fmt in 'png bmp jpeg'.split(): d = image_to_data(img, fmt=fmt) image_from_data(d) # Run the imaging tests test() from calibre.gui2 import Application os.environ.pop('DISPLAY', None) has_headless = isosx or islinux app = Application([], headless=has_headless) self.assertGreaterEqual(len(QFontDatabase().families()), 5, 'The QPA headless plugin is not able to locate enough system fonts via fontconfig') if has_headless: from calibre.ebooks.covers import create_cover create_cover('xxx', ['yyy']) na = QNetworkAccessManager() self.assertTrue(hasattr(na, 'sslErrors'), 'Qt not compiled with openssl') from PyQt5.QtWebKitWidgets import QWebView if iswindows: from PyQt5.Qt import QtWin QtWin QWebView() del QWebView del na del app
############################################################################### # FILE MANAGER ############################################################################### # File types supported by Ninja-IDE FILE_TYPES = [ ("Python files", (".py", ".pyw")), ("QML files", (".qml",)), ("HTML document", (".html", ".htm")), ("JavaScript program", (".js", ".jsm")), ("Ninja project", (".nja",)) ] # Mime types image_mimetypes = [f.data().decode() for f in QImageReader.supportedMimeTypes()][1:] db = QMimeDatabase() for mt in image_mimetypes: mimetype = db.mimeTypeForName(mt) suffixes = [".{}".format(s) for s in mimetype.suffixes()] FILE_TYPES.append((mimetype.comment(), suffixes)) LANGUAGE_MAP = { "py": "python", "pyw": "python", "js": "javascript", "html": "html", "md": "markdown", "yml": "yaml", "qml": "qml",
def initializeLayer(self, screenExtent=None): if self.error or self.initialized or self.initializing: return if self.filepath is not None: # not safe... self.initializing = True filepath = self.getAbsoluteFilepath() if not os.path.exists(filepath): # TODO integrate with BadLayerHandler ? loadErrorDialog = LoadErrorDialog(filepath) result = loadErrorDialog.exec_() if result == 1: # absolute filepath = loadErrorDialog.lineEditImagePath.text() # to relative if needed self.filepath = utils.toRelativeToQGS(filepath) self.setCustomProperty("filepath", self.filepath) QgsProject.instance().setDirty(True) else: self.error = True del loadErrorDialog fileInfo = QFileInfo(filepath) ext = fileInfo.suffix() if ext == "pdf": s = QSettings() oldValidation = s.value("/Projections/defaultBehavior") s.setValue("/Projections/defaultBehavior", "useGlobal") # for not asking about crs path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) self.image = layer.previewAsImage(QSize(layer.width(),layer.height())) s.setValue("/Projections/defaultBehavior", oldValidation) else: reader = QImageReader(filepath) self.image = reader.read() self.initialized = True self.initializing = False self.setupCrs() if screenExtent: # constructor called from AddLayer action # if not, layer loaded from QGS project file # check if image already has georef info # use GDAL dataset = gdal.Open(filepath, gdal.GA_ReadOnly) georef = None if dataset: georef = dataset.GetGeoTransform() if georef and not self.is_default_geotransform(georef): self.initializeExistingGeoreferencing(dataset, georef) else: # init to default params self.setCenter(screenExtent.center()) self.setRotation(0.0) sw = screenExtent.width() sh = screenExtent.height() self.resetScale(sw, sh) self.commitTransformParameters()
def readableImageFormatsFilter(): return toImageFileFilter(QImageReader.supportedImageFormats())