def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tupple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() image = image.copy(x1, y1, w, h) else: self.currentFrame().setScrollBarPolicy(QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self.currentFrame().setScrollBarPolicy(QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self.setViewportSize(self.currentFrame().contentsSize()) image = QImage(self.viewportSize(), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() return image
def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tupple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() image = image.copy(x1, y1, w, h) else: self.currentFrame().setScrollBarPolicy( QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff) self.currentFrame().setScrollBarPolicy( QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff) self.setViewportSize(self.currentFrame().contentsSize()) image = QImage(self.viewportSize(), format) painter = QPainter(image) self.currentFrame().render(painter) painter.end() return image
def capture(self, region=None, selector=None, format=QImage.Format_ARGB32_Premultiplied): """Returns snapshot as QImage. :param region: An optional tupple containing region as pixel coodinates. :param selector: A selector targeted the element to crop on. :param format: The output image format. """ if region is None and selector is not None: region = self.region_for_selector(selector) if region: x1, y1, x2, y2 = region w, h = (x2 - x1), (y2 - y1) image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() image = image.copy(x1, y1, w, h) else: image = QImage(self.page.viewportSize(), format) painter = QPainter(image) self.main_frame.render(painter) painter.end() return image
def snapshot(self, box=None, format=QImage.Format_ARGB32): """ Take an image snapshot of the current frame. @param box: 4-element tuple containing box to capture (x1, y1, x2, y2). If None, capture the whole page. @param format: QImage format (see QImage::Format_*). @return: A QImage image. Typical usage: >>> browser.load(url) >>> browser.snapshot().save("webpage.png") """ if box: x1, y1, x2, y2 = box w, h = (x2 - x1), (y2 - y1) image0 = QImage(QSize(x2, y2), format) painter = QPainter(image0) self.webpage.mainFrame().render(painter) painter.end() image = image0.copy(x1, y1, w, h) else: image = QImage(self.webpage.viewportSize(), format) painter = QPainter(image) self.webpage.mainFrame().render(painter) painter.end() return image
def get_indexed(data, w, h, colors=256, crop=True): palette = data[:colors * 4] table = [] for i in range(colors): b = palette[(i * 4) + 0] g = palette[(i * 4) + 1] r = palette[(i * 4) + 2] a = palette[(i * 4) + 3] table.append(qRgba(r, g, b, a)) img_start = colors * 4 mask_start = img_start + (w * h) image = data[img_start:mask_start] image = QImage(image, w, h, QImage.Format_Indexed8) image.setColorTable(table) image = image.convertToFormat(QImage.Format_ARGB32) mask = data[mask_start:] for i in range(len(mask)): x = i % w y = i / w pixel = image.pixel(x, y) pixel = qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel), mask[i]) image.setPixel(x, y, pixel) if crop: image = image.copy(0, 0, w - 2, h - 2) return image, len(mask) > 0
def _svgMarkerSymbol(name, sprites): #TODO: see if there is a built-in sprite with that name with open(sprites + ".json") as f: spritesDict = json.load(f) rect = QRect(spritesDict[name]["x"], spritesDict[name]["y"], spritesDict[name]["width"], spritesDict[name]["height"]) width = spritesDict[name]["width"] height = spritesDict[name]["height"] image = QImage() image.load(sprites + ".png") sprite = image.copy(rect) pngPath = os.path.join(os.path.dirname(sprites), name + ".png") sprite.save(pngPath) with open(pngPath, "rb") as f: data = f.read() base64 = data.encode("base64") svgPath = os.path.join(os.path.dirname(sprites), name + ".svg") with open(svgPath, "w") as f: f.write symbol = QgsMarkerSymbolV2() symbolLayer = QgsSvgMarkerSymbolLayerV2(svgPath) symbol.setSize(max([width, height])) symbol.appendSymbolLayer(symbolLayer) symbol.deleteSymbolLayer(0) return symbol
def to_QImage(self): self._decode() if self.format == PackedQImage.FORMAT_ARGB32: return QImage(self.buf, self.w, self.h, QImage.Format_ARGB32).copy() elif self.format == PackedQImage.FORMAT_PNG: img = QImage() img.loadFromData(self.buf, format='PNG') return img.copy()
def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888); return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32); return qim.copy() if copy else qim
def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888); return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32); return qim.copy() if copy else qim raise NotImplementedException('no conversion to QImage implemented for given image type (depth: %s, shape: %s)' % (im.dtype, im.shape))
def toQImage(im, copy=False): if im is None: return QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() if copy else qim elif len(im.shape) == 3: if im.shape[2] == 3: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888) return qim.copy() if copy else qim elif im.shape[2] == 4: qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32) return qim.copy() if copy else qim raise NotImplementedException('no conversion to QImage implemented for given image type (depth: %s, shape: %s)' % (im.dtype, im.shape))
def get_grayscale(data, w, h, crop=True): table = [] for i in range(256): table.append((255 << 24) | (i << 16) | (i << 8) | i) image = QImage(data, w, h, QImage.Format_Indexed8) image.setColorTable(table) image = image.convertToFormat(QImage.Format_ARGB32) if crop: image = image.copy(0, 0, w - 2, h - 2) return image
def _getPng(self, width=None, height=None): image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") return bytes(b.data())
def _render(self): self.setViewportSize(QSize(self.vwidth, self.vheight)) image = QImage(self.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.mainFrame().render(painter) painter.end() if self.width: image = image.scaledToWidth(self.width, Qt.SmoothTransformation) if self.height: image = image.copy(0, 0, self.width, self.height) b = QBuffer() image.save(b, "png") return str(b.data())
def np_to_qimage(np_img, copy=False): gray_color_table = [qRgb(i, i, i) for i in range(256)] if np_img is None: return QImage() if np_img.dtype != np.uint8: print np_img.dtype np.clip(np_img, 0, 255, out=np_img) np_img = np_img.astype('uint8') if len(np_img.shape) == 2: qimg = QImage(np_img.data, np_img.shape[1], np_img.shape[0], np_img.strides[0], QImage.Format_Indexed8) qimg.setColorTable(gray_color_table) return qimg.copy() if copy else qimg elif len(np_img.shape) == 3: if np_img.shape[2] == 3: qimg = QImage(np_img.data, np_img.shape[1], np_img.shape[0], np_img.strides[0], QImage.Format_RGB888) return qimg.copy() if copy else qimg elif np_img.shape[2] == 4: qimg = QImage(np_img.data, np_img.shape[1], np_img.shape[0], np_img.strides[0], QImage.Format_ARGB32) return qimg.copy() if copy else qimg raise NotImplementedError
def plotAnnotationImages(self, width, height, image_format = QImage.Format_ARGB32_Premultiplied): """Plots the annotations for the product specified in the current input file on an image with the specified width and height, and optionally specified image format. Each annotation image is yielded by this generator method.""" image = QImage(width, height, image_format) image, rectangles, annotationTransform = self._plot(width, height, image, self.controller, self.controller.plotAnnotations) for rectangle in rectangles: sr = QRect(rectangle.x1, rectangle.y1, rectangle.width(), rectangle.height()) dr = annotationTransform.mapRect(sr) yield image.copy(dr)
def combineTiles(self): global radar1 ii = QImage(self.tilesWidth * 256, self.tilesHeight * 256, QImage.Format_ARGB32) painter = QPainter() painter.begin(ii) painter.setPen(QColor(255, 255, 255, 255)) painter.setFont(QFont("Arial", 10)) i = 0 xo = self.cornerTiles["NW"]["X"] xo = int((int(xo) - xo) * 256) yo = self.cornerTiles["NW"]["Y"] yo = int((int(yo) - yo) * 256) for y in range(0, self.totalHeight, 256): for x in range(0, self.totalWidth, 256): if self.tileQimages[i].format() == 5: painter.drawImage(x, y, self.tileQimages[i]) # painter.drawRect(x, y, 255, 255) # painter.drawText(x+3, y+12, self.tiletails[i]) i += 1 painter.end() painter = None self.tileQimages = [] ii2 = ii.copy(-xo, -yo, self.rect.width(), self.rect.height()) ii = None painter2 = QPainter() painter2.begin(ii2) timestamp = "{0:%H:%M} rainvewer.com".format( datetime.datetime.fromtimestamp(self.getTime)) painter2.setPen(QColor(63, 63, 63, 255)) painter2.setFont(QFont("Arial", 8)) painter2.setRenderHint(QPainter.TextAntialiasing) painter2.drawText(3 - 1, 12 - 1, timestamp) painter2.drawText(3 + 2, 12 + 1, timestamp) painter2.setPen(QColor(255, 255, 255, 255)) painter2.drawText(3, 12, timestamp) painter2.drawText(3 + 1, 12, timestamp) painter2.end() painter2 = None ii3 = QPixmap(ii2) ii2 = None self.frameImages.append({"time": self.getTime, "image": ii3}) ii3 = None
def _getPng(self, width=None, height=None, b64=False): self.log("getting PNG %s" % id(self.splash_request)) image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() self.web_page.har_log.store_timing("_onScreenshotPrepared") if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") result = bytes(b.data()) if b64: result = base64.b64encode(result) self.web_page.har_log.store_timing("_onPngRendered") return result
def png(self, width=None, height=None, b64=False): """ Return screenshot in PNG format """ self.logger.log("getting PNG", min_level=2) image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() self.store_har_timing("_onScreenshotPrepared") if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") result = bytes(b.data()) if b64: result = base64.b64encode(result) self.store_har_timing("_onPngRendered") return result
def _getSvgPath(name, sprites): #TODO: see if there is a built-in sprite with that name if name is None: return None, None with open(sprites + ".json") as f: spritesDict = json.load(f) rect = QRect(spritesDict[name]["x"], spritesDict[name]["y"], spritesDict[name]["width"], spritesDict[name]["height"]) width = spritesDict[name]["width"] height = spritesDict[name]["height"] image = QImage() image.load(sprites + ".png") sprite = image.copy(rect) pngPath = os.path.join(os.path.dirname(sprites), name + ".png") sprite.save(pngPath) with open(pngPath, "rb") as f: data = f.read() base64 = data.encode("base64") svgPath = os.path.join(os.path.dirname(sprites), name + ".svg") with open(svgPath, "w") as f: f.write(_svgTemplate % {"w": width, "h": height, "b64": base64}) return svgPath, max([width, height])
def save_snapshot(self, filename="snapshot.png", element=None): """Take an image snapshot of the current frame. If a specific element is specified, only grab the image of that one element. """ format = QImage.Format_ARGB32 # First reset the viewport, then set it to the content size. If the # viewport is not reset, the resulting image might be larger than # necessary. self.webpage.setViewportSize(QSize(1, 1)) self.webpage.setViewportSize(self.webframe.contentsSize()) if element is None: image = QImage(self.webframe.contentsSize(), format) painter = QPainter(image) self.webframe.render(painter) painter.end() else: # If element is actually a CSS selector: if isinstance(element, basestring): element = self._first(element) rect = element.geometry() w, h = rect.width(), rect.height() x1 = rect.x() y1 = rect.y() x2 = x1 + w y2 = y1 + h image = QImage(QSize(x2, y2), format) painter = QPainter(image) self.webframe.render(painter) painter.end() image = image.copy(x1, y1, w, h) image.save(filename)
def get_rgba(data, w, h, crop=True): image = adjust_scanline(data, w) image = QImage(image, w, h, QImage.Format_ARGB32) if crop: image = image.copy(0, 0, w - 2, h - 2) return image