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 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(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 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)
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 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 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 _load(self, path: str, reload_only: bool): """Load proper displayable QWidget for a path. This reads the image using QImageReader and then emits the appropriate *_loaded signal to tell the image to display a new object. """ # Pass file format explicitly as imghdr does a much better job at this than the # file name based approach of QImageReader file_format = files.imghdr.what(path) if file_format is None: log.error("%s is not a valid image", path) return reader = QImageReader(path, file_format.encode("utf-8")) reader.setAutoTransform(True) # Automatically apply exif orientation if not reader.canRead(): log.error("Cannot read image %s", path) return # SVG if file_format == "svg" and QSvgWidget: # Do not store image and only emit with the path as the # VectorGraphic widget needs the path in the constructor self.original = None api.signals.svg_loaded.emit(path, reload_only) self._image_type = ImageType.Svg # Gif elif reader.supportsAnimation(): movie = QMovie(path) if not movie.isValid() or movie.frameCount() == 0: log.error("Error reading animation %s: invalid data", path) return self.original = movie api.signals.movie_loaded.emit(self.current, reload_only) self._image_type = ImageType.Movie # Regular image else: pixmap = QPixmap.fromImageReader(reader) if reader.error(): log.error("Error reading image %s: %s", path, reader.errorString()) return self.original = pixmap api.signals.pixmap_loaded.emit(self.current, reload_only) self._image_type = ImageType.Pixmap self._path = path
def icon_for_game(game, size, icon_cache, filecache_root, category="icon", imode="qt"): cur = icon_in_cache(game, size, icon_cache, filecache_root, category, imode) if cur: return cur fpath, mode, url = path_to_icon(game, filecache_root, category) if not os.path.exists(fpath): p = None #p == image bytes or a local file path that Image can .open() if mode == "download": print("Download icon:", url) r = requests.get(url, headers=headers) p = BytesIO(r.content) elif mode == "extract": print("Extract icon:", url.encode("ascii", "backslashreplace")) p = extract_icons.get_icon(url, filecache_root) elif mode == "gba": print("Download gba icon:", url) p = extract_icons.get_gba(url) elif mode == "generate": print("Generate custom icon:", url) generate_icon(fpath, game, filecache_root) #Save all images as .png if p: try: pil_image = Image.open(p) except OSError: print("None image provided, no icon loaded:", url) else: pil_image.save(fpath) if os.path.exists(fpath) and not (fpath, size) in icon_cache: if imode == "path": return fpath.replace("/", os.path.sep) elif imode == "qt": mode = "" with open(fpath.replace("/", os.path.sep), "rb") as f: head = str(f.read(20)) if "JFIF" in head: mode = "JPG" img = QImageReader(fpath.replace("/", os.path.sep)) qp = QPixmap.fromImageReader(img) if not qp.isNull(): if category == "icon": mode = Qt.IgnoreAspectRatio if category == "logo": mode = Qt.KeepAspectRatio qp = qp.scaled(size, size, mode, Qt.SmoothTransformation) else: print("error loading", repr(fpath), mode) icon_cache[(fpath, size)] = qp else: try: icon_cache[(fpath, size)] = pygame.transform.scale( pygame.image.load(fpath), [size, size]) except: pass return icon_in_cache(game, size, icon_cache, filecache_root, category, imode)