def get_movie_icon(file_id): icon_file = os.path.join(MOVIE_DIR, "movie_%03d.png" % file_id) border_file = os.path.join(MOVIE_DIR, "clip.png") if not os.path.isfile(icon_file): icon_file = os.path.join(MOVIE_DIR, "movie_%03d.png" % 999) icon = QImage(icon_file) border = QImage(border_file) x_pos = 10 y_pos = 45 x_offset = 29 y_offset = 88 out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) painter.drawImage(QRect(x_pos, y_pos, border.width(), border.height()), border, border.rect()) painter.drawImage(QRect(x_pos + x_offset, y_pos + y_offset, icon.width(), icon.height()), icon, icon.rect()) painter.end() return out
def _exportCompositionAsImage(self, composition, filePath): """ Export the composition as a raster image. """ #Image size dpi = composition.printResolution() dpmm = dpi / 25.4 width = int(dpmm * composition.paperWidth()) height = int(dpmm * composition.paperHeight()) #Create output image and initialize it image = QImage(QSize(width, height), QImage.Format_ARGB32) image.setDotsPerMeterX(dpmm * 1000) image.setDotsPerMeterY(dpmm * 1000) image.fill(0) #Render the composition imagePainter = QPainter(image) sourceArea = QRectF(0, 0, composition.paperWidth(), composition.paperHeight()) targetArea = QRectF(0, 0, width, height) composition.render(imagePainter, targetArea, sourceArea) imagePainter.end() image.save(filePath)
def _renderedImage2(self, width, height, extent, transp_background=False, layerids=None): """rendering function for GIS < 2.7""" antialias = True if self._renderer is None: self._initRenderer() canvas = self.exportSettings.canvas if canvas is None: logMessage("With this QGIS version (<= 2.6), map canvas needs to be set to the export settings") return if layerids is None: layerids = [mapLayer.id() for mapLayer in canvas.layers()] renderer = self._renderer # QgsMapRenderer renderer.setLayerSet(layerids) image = QImage(width, height, QImage.Format_ARGB32_Premultiplied) if transp_background: image.fill(QColor(Qt.transparent).rgba()) # else: image.fill(canvas.canvasColor().rgba()) # renderer.setOutputSize(image.size(), image.logicalDpiX()) renderer.setExtent(extent.unrotatedRect()) painter = QPainter() painter.begin(image) if antialias: painter.setRenderHint(QPainter.Antialiasing) renderer.render(painter) painter.end() return tools.base64image(image)
def _render_qwebpage_full(self, web_rect, render_rect, canvas_size): """Render web page in one step.""" if self._qpainter_needs_tiling(render_rect, canvas_size): # If this condition is true, this function may get stuck. raise ValueError("Rendering region is too large to be drawn" " in one step, use tile-by-tile renderer instead") canvas = QImage(canvas_size, self.qt_image_format) if self.is_jpeg(): # White background for JPEG images, same as we have in all browsers. canvas.fill(Qt.white) else: # Preserve old behaviour for PNG format. canvas.fill(0) painter = QPainter(canvas) try: painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.setWindow(web_rect) painter.setViewport(render_rect) painter.setClipRect(web_rect) self.web_page.mainFrame().render(painter) finally: painter.end() return WrappedQImage(canvas)
def _renderedImage2(self, width, height, extent, transp_background=False, layerids=None): antialias = True if self._renderer is None: self._initRenderer() canvas = self.context.canvas if layerids is None: layerids = [mapLayer.id() for mapLayer in canvas.layers()] renderer = self._renderer renderer.setLayerSet(layerids) image = QImage(width, height, QImage.Format_ARGB32_Premultiplied) if transp_background: image.fill(QColor(Qt.transparent).rgba()) # else: image.fill(canvas.canvasColor().rgba()) # renderer.setOutputSize(image.size(), image.logicalDpiX()) renderer.setExtent(extent.unrotatedRect()) painter = QPainter() painter.begin(image) if antialias: painter.setRenderHint(QPainter.Antialiasing) renderer.render(painter) painter.end() return tools.base64image(image)
def get_text(text, scene_mode = common.SCENE_MODES.debate, format = TextFormat(), mangle = True): lines, lengths, clt_changes = process_text(text, scene_mode, format, False) # For our borders, since I'm lazy. margin = 1 img_h = len(lines) * format.h + (margin * 2) img_w = 0 x, y = 0, 0 for length in lengths: width = sum(length) + (margin * 2) if width > img_w: img_w = width if format.orient == TEXT_ORIENT.ver: img_w, img_h = img_h, img_w + format.h x = img_w - format.h - margin out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) new_format = copy.copy(format) new_format.x = x new_format.y = y new_format.w = img_w return print_text(out, text, scene_mode, new_format, mangle)
def paintEvent(self, event): super(DetailedProgress, self).paintEvent(event) if not self._current_progress: return painter = QPainter(self) width = self.width() height = self.height() aspect_ratio = float(width)/height nr_realizations = len(self._current_progress) fm_size = len(self._current_progress[0][1]) self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio)) self.grid_width = math.ceil(self.grid_height * aspect_ratio) sub_grid_size = math.ceil(math.sqrt(fm_size)) cell_height = height / self.grid_height cell_width = width / self.grid_width foreground_image = QImage(self.grid_width*sub_grid_size, self.grid_height*sub_grid_size, QImage.Format_ARGB32) foreground_image.fill(QColor(0, 0, 0, 0)) for index, (iens, progress) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) self.draw_window(x * sub_grid_size, y * sub_grid_size, progress, foreground_image) painter.drawImage(self.contentsRect(), foreground_image) for index, (iens, progress) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) if iens == self.selected_realization: painter.setPen(QColor(240, 240, 240)) else: painter.setPen(QColor(80, 80, 80)) painter.drawRect(x * cell_width, y * cell_height, cell_width-1, cell_height-1) painter.drawText(x * cell_width + cell_width / 2, y * cell_height + cell_height / 2, str(iens))
def get_sprite(sprite_id): sprite_file = get_sprite_file(sprite_id) if sprite_file == None: return None sprite_file = os.path.join(SPRITE_DIR, sprite_file) if not os.path.isfile(sprite_file): sprite_file = os.path.join(SPRITE_DIR, "bustup_%02d_%02d.png" % (99, 99)) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) sprite = QImage(sprite_file) # Center the sprite on our image. sprite_x = (out.width() - sprite.width()) / 2 sprite_y = 0 painter.drawImage(QRect(sprite_x, sprite_y, sprite.width(), sprite.height()), sprite, sprite.rect()) painter.end() return out
def get_ammo(ammo_id, x, y): if ammo_id == -1: return None ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % ammo_id) ammo_border_file = os.path.join(AMMO_DIR, "border.png") if not os.path.isfile(ammo_file): ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % 999) ammo = QImage(ammo_file) border = QImage(ammo_border_file) x_pos = x y_pos = y border_x = x_pos - ((border.width() - ammo.width()) / 2) border_y = y_pos - ((border.height() - ammo.height()) / 2) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) painter.drawImage(QRect(x_pos, y_pos, ammo.width(), ammo.height()), ammo, ammo.rect()) painter.drawImage(QRect(border_x, border_y, border.width(), border.height()), border, border.rect()) painter.end() return out
def updateTerritoryOwner(self, name, owner): t = self.game.board.getTerritory(name) p = self.game.getPlayer(owner) color = QColor(*p.color) color.setAlpha(200) territoryImage = QImage(t.image.size(), QImage.Format_ARGB32_Premultiplied) p = QPainter() p.begin(territoryImage) p.drawImage(0, 0, self.game.board.image) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.drawImage(0, 0, t.image) p.end() coloredTerritoryImage = QImage(territoryImage.size(), QImage.Format_ARGB32_Premultiplied) coloredTerritoryImage.fill(0) p.begin(coloredTerritoryImage) p.fillRect(territoryImage.rect(), color) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.drawImage(0, 0, t.image) p.end() p.begin(self.ownershipMap) p.drawImage(0, 0, territoryImage) p.drawImage(0, 0, coloredTerritoryImage) p.end() self.scaledOwnershipMap = self.ownershipMap.scaled(self.imageSize()) self.update()
def get_cutin(cutin_id): if cutin_id == -1: return None cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % cutin_id) cutin_border_file = os.path.join(CUTIN_DIR, "border.png") if not os.path.isfile(cutin_file): cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % 999) cutin = QImage(cutin_file) border = QImage(cutin_border_file) x_pos = 307 y_pos = 91 border_x = x_pos - ((border.width() - cutin.width()) / 2) border_y = y_pos - ((border.height() - cutin.height()) / 2) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) painter.drawImage(QRect(x_pos, y_pos, cutin.width(), cutin.height()), cutin, cutin.rect()) painter.drawImage( QRect(border_x, border_y, border.width(), border.height()), border, border.rect()) painter.end() return out
def exportAsImage(self): filename = unicode( QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)'))) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = QRectF(0, 0, 1, 1) for item in self.scene.items(): totalRect = totalRect.united(item.sceneBoundingRect()) totalRect.adjust(-10, -10, 10, 10) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, totalRect, totalRect) painter.end() img.save(filename)
def _get_composer_image(self, width, height, dpi): image = QImage(QSize(width, height), self._TestMapSettings.outputImageFormat()) image.fill(QColor(152, 219, 249).rgb()) image.setDotsPerMeterX(dpi / 25.4 * 1000) image.setDotsPerMeterY(dpi / 25.4 * 1000) p = QPainter(image) p.setRenderHint( QPainter.Antialiasing, self._TestMapSettings.testFlag(QgsMapSettings.Antialiasing) ) self._c.renderPage(p, 0) p.end() # image = self._c.printPageAsRaster(0) # """:type: QImage""" if image.isNull(): return False, '' filepath = getTempfilePath('png') res = image.save(filepath, 'png') if not res: os.unlink(filepath) filepath = '' return res, filepath
def make_piece_from_path(o, piece_id, qpainter_path): # generate the mask, and call back to actually create the piec. path = qpainter_path path.closeSubpath() #determine the required size of the mask mask_rect = path.boundingRect().toAlignedRect() #create the mask mask = QImage(mask_rect.size(), QImage.Format_ARGB32_Premultiplied) # fully transparent color mask.fill(0x00000000) painter = QPainter(mask) painter.translate(-mask_rect.topLeft()) #we explicitly use a pen stroke in order to let the pieces overlap a bit (which reduces rendering glitches at the edges where puzzle pieces touch) # 1.0 still leaves the slightest trace of a glitch. but making the stroke thicker makes the plugs appear non-matching even when they belong together. # 2016-06-18: changed to 0.5 -- bevel looks better painter.setPen(QPen(Qt.black, 0.5)) if o.outline_only: painter.setBrush(Qt.NoBrush) else: painter.setBrush(Qt.SolidPattern) painter.setRenderHint(QPainter.Antialiasing) painter.drawPath(path) painter.end() o.add_piece_func(piece_id=piece_id, mask_image=mask, offset=mask_rect.topLeft())
class GameFont: def __init__(self, width=512): self.trans = QImage(width, MAX_HEIGHT, QImage.Format_ARGB32_Premultiplied) self.trans.fill(QColor(0, 0, 0, 0).rgba()) self.opaque = QImage(width, MAX_HEIGHT, QImage.Format_ARGB32_Premultiplied) self.opaque.fill(QColor(0, 0, 0, 255).rgba()) self.font_data = FontData() def save(self, directory, name, for_game=True, for_editor=True, font_type=FONT_TYPES.font01, game=GAMES.dr): # name = str(font_type) if for_editor: self.trans.save(os.path.join(directory, name + ".png")) if for_game: opaque_gray = to_gray(self.opaque) opaque_gray.save(os.path.join(directory, name + ".bmp")) self.font_data.save(os.path.join(directory, name + ".font"), font_type, game)
def get_text(text, scene_mode=common.SCENE_MODES.debate, format=TextFormat(), mangle=True): lines, lengths, clt_changes = process_text(text, scene_mode, format, False) # For our borders, since I'm lazy. margin = 1 img_h = len(lines) * format.h + (margin * 2) img_w = 0 x, y = 0, 0 for length in lengths: width = sum(length) + (margin * 2) if width > img_w: img_w = width if format.orient == TEXT_ORIENT.ver: img_w, img_h = img_h, img_w + format.h x = img_w - format.h - margin out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) new_format = copy.copy(format) new_format.x = x new_format.y = y new_format.w = img_w return print_text(out, text, scene_mode, new_format, mangle)
def _get_composer_image(self, width, height, dpi): image = QImage(QSize(width, height), self._TestMapSettings.outputImageFormat()) image.fill(QColor(152, 219, 249).rgb()) image.setDotsPerMeterX(dpi / 25.4 * 1000) image.setDotsPerMeterY(dpi / 25.4 * 1000) p = QPainter(image) p.setRenderHint( QPainter.Antialiasing, self._TestMapSettings.testFlag(QgsMapSettings.Antialiasing)) self._c.renderPage(p, 0) p.end() # image = self._c.printPageAsRaster(0) # """:type: QImage""" if image.isNull(): return False, '' filepath = getTempfilePath('png') res = image.save(filepath, 'png') if not res: os.unlink(filepath) filepath = '' return res, filepath
def compose_image(self): """ This loops through all the tiles and then composes a single map canvas renderable image :return: a renderable image :rtype: QImage """ width = (self.xmax - self.xmin + 1) * self.layerDef.TILE_SIZE height = (self.ymax - self.ymin + 1) * self.layerDef.TILE_SIZE image = QImage(width, height, QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent) p = QPainter(image) for tile in self.tiles.values(): if not tile.pixel_data: continue x = tile.x - self.xmin y = tile.y - self.ymin rect = QRect(x * self.layerDef.TILE_SIZE, y * self.layerDef.TILE_SIZE, self.layerDef.TILE_SIZE, self.layerDef.TILE_SIZE) timg = QImage() timg.loadFromData(tile.pixel_data) p.drawImage(rect, timg) return image
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap( mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def exportAsImage(self): filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)'))) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = QRectF(0, 0, 1, 1) for item in self.scene.items(): totalRect = totalRect.united(item.sceneBoundingRect()) totalRect.adjust(-10, -10, 10, 10) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, totalRect, totalRect) painter.end() img.save(filename)
def get_cutin(cutin_id): if cutin_id == -1: return None cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % cutin_id) cutin_border_file = os.path.join(CUTIN_DIR, "border.png") if not os.path.isfile(cutin_file): cutin_file = os.path.join(CUTIN_DIR, "cutin_ico_%03d.png" % 999) cutin = QImage(cutin_file) border = QImage(cutin_border_file) x_pos = 307 y_pos = 91 border_x = x_pos - ((border.width() - cutin.width()) / 2) border_y = y_pos - ((border.height() - cutin.height()) / 2) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) painter.drawImage(QRect(x_pos, y_pos, cutin.width(), cutin.height()), cutin, cutin.rect()) painter.drawImage(QRect(border_x, border_y, border.width(), border.height()), border, border.rect()) painter.end() return out
def endDrawing(self, pos): has_moved = self._hasMoved # _hasMoved will change after calling moveTo if has_moved: self.moveTo(pos) else: assert(self.pos == pos) self.moveTo(QPointF(pos.x()+0.0001, pos.y()+0.0001)) # move a little tempi = QImage(QSize(self.bb.width(), self.bb.height()), QImage.Format_ARGB32_Premultiplied) #TODO: format tempi.fill(0) painter = QPainter(tempi) self.scene.render(painter, target=QRectF(), source=QRectF(QPointF(self.bb.x(), self.bb.y()), QSizeF(self.bb.width(), self.bb.height()))) painter.end() ndarr = qimage2ndarray.rgb_view(tempi)[:,:,0] labels = numpy.where(ndarr>0,numpy.uint8(self.drawnNumber),numpy.uint8(0)) labels = labels.swapaxes(0,1) assert labels.shape[0] == self.bb.width() assert labels.shape[1] == self.bb.height() ## ## ensure that at least one pixel is label when the brush size is 1 ## ## this happens when the user just clicked without moving ## in that case the lineitem will be so tiny, that it won't be rendered ## into a single pixel by the code above if not has_moved and self.brushSize <= 1 and numpy.count_nonzero(labels) == 0: labels[labels.shape[0]//2, labels.shape[1]//2] = self.drawnNumber self.brushStrokeAvailable.emit(QPointF(self.bb.x(), self.bb.y()), labels)
def processAlgorithm(self, progress): m = self.get_mesh(self.IN_CF_MESH) o = self.get_bed_elevation(m) output_filename = self.getOutputValue(self.OUT_CF_IMG) w = self.getParameterValue(self.IN_CF_W) h = self.getParameterValue(self.IN_CF_H) size = (w, h) extent = m.extent() muppx = (extent[2] - extent[0]) / size[0] muppy = (extent[3] - extent[1]) / size[1] mupp = max(muppx, muppy) cx = (extent[2] + extent[0]) / 2 cy = (extent[3] + extent[1]) / 2 ll = (cx - (size[0] / 2) * mupp, cy - (size[1] / 2) * mupp) rconfig = RendererConfig() rconfig.set_view(size, ll, mupp) rconfig.set_output_mesh(m) rconfig.set_output_contour(o) img = QImage(size[0], size[1], QImage.Format_ARGB32) img.fill(0) r = Renderer(rconfig, img) r.draw() img.save(output_filename)
def _render_qwebpage_full(web_page, logger, viewport_size, image_size): image = QImage(image_size, QImage.Format_ARGB32) image.fill(0) painter = QPainter(image) try: painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.setWindow(QRect(QPoint(0, 0), web_page.viewportSize())) painter.setViewport(QRect(QPoint(0, 0), viewport_size)) if image_size != viewport_size: # Try not to draw stuff that won't fit into the image. Clipping # must be specified in input (aka logical) coordinates, but we know # it in output (aka physical) coordinates, so we have to do an # inverse transformation. If, for some reason, we cannot, skip the # clipping altogether. clip_rect = QRect(QPoint(0, 0), viewport_size) inv_transform, invertible = painter.combinedTransform().inverted() if invertible: painter.setClipRect(inv_transform.mapRect(clip_rect)) web_page.mainFrame().render(painter) finally: # It is important to end painter explicitly in python code, because # Python finalizer invocation order, unlike C++ destructors, is not # deterministic and there is a possibility of image's finalizer running # before painter's which may break tests and kill your cat. painter.end() return qimage_to_pil_image(image)
def updateMask(control_image_path, rendered_image_path, mask_image_path): control_image = imageFromPath(control_image_path) if not control_image: error('Could not read control image {}'.format(control_image_path)) rendered_image = imageFromPath(rendered_image_path) if not rendered_image: error('Could not read rendered image {}'.format(rendered_image_path)) if not rendered_image.width() == control_image.width( ) or not rendered_image.height() == control_image.height(): print( 'Size mismatch - control image is {}x{}, rendered image is {}x{}'. format(control_image.width(), control_image.height(), rendered_image.width(), rendered_image.height())) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) #read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): print 'Mask image does not exist, creating {}'.format(mask_image_path) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) #loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in xrange(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in xrange(max_width): currentTolerance = qRed( struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: #ignore pixel continue expected_rgb = struct.unpack('I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack('I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: #update mask image mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 if mismatch_count: #update mask mask_image.save(mask_image_path, "png") print 'Updated {} pixels in {}'.format(mismatch_count, mask_image_path) else: print 'No mismatches in {}'.format(mask_image_path)
def get_sprite(sprite_id): sprite_file = get_sprite_file(sprite_id) if sprite_file == None: return None sprite_file = os.path.join(SPRITE_DIR, sprite_file) if not os.path.isfile(sprite_file): sprite_file = os.path.join(SPRITE_DIR, "bustup_%02d_%02d.png" % (99, 99)) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) sprite = QImage(sprite_file) # Center the sprite on our image. sprite_x = (out.width() - sprite.width()) / 2 sprite_y = 0 painter.drawImage( QRect(sprite_x, sprite_y, sprite.width(), sprite.height()), sprite, sprite.rect()) painter.end() return out
def get_ammo(ammo_id, x, y): if ammo_id == -1: return None ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % ammo_id) ammo_border_file = os.path.join(AMMO_DIR, "border.png") if not os.path.isfile(ammo_file): ammo_file = os.path.join(AMMO_DIR, "kotodama_ico_%03d.png" % 999) ammo = QImage(ammo_file) border = QImage(ammo_border_file) x_pos = x y_pos = y border_x = x_pos - ((border.width() - ammo.width()) / 2) border_y = y_pos - ((border.height() - ammo.height()) / 2) out = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) painter.drawImage(QRect(x_pos, y_pos, ammo.width(), ammo.height()), ammo, ammo.rect()) painter.drawImage( QRect(border_x, border_y, border.width(), border.height()), border, border.rect()) painter.end() return out
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
class ScribbleArea(QWidget): """ this scales the image but it's not good, too many refreshes really mess it up!!! """ def __init__(self, w, h, parent=None): super(ScribbleArea, self).__init__(parent) self.setAttribute(Qt.WA_StaticContents) self.scribbling = 0 self.width = w self.height = h self.image_pen_width = 5 self.pen_width = 1 self.image = QImage(QSize(w, h), QImage.Format_RGB32) self.setMaximumSize(w*self.image_pen_width, w*self.image_pen_width) self.setMinimumSize(w*self.image_pen_width, h*self.image_pen_width) self.last_point = QPoint() self.clear_image() def clear_image(self): self.image.fill(Qt.black) self.update() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.last_point = event.pos() self.scribbling = 1 elif event.button() == Qt.RightButton: self.last_point = event.pos() self.scribbling = 2 def mouseMoveEvent(self, event): if (event.buttons() & Qt.LeftButton) and self.scribbling == 1: self.draw_line_to(event.pos()) elif (event.buttons() & Qt.RightButton) and self.scribbling == 2: self.draw_line_to(event.pos()) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and self.scribbling == 1: self.draw_line_to(event.pos()) self.scribbling = 0 elif event.button() == Qt.RightButton and self.scribbling == 2: self.draw_line_to(event.pos()) self.scribbling = 0 def paintEvent(self, event): painter = QPainter(self) painter.drawImage(event.rect(), self.image.scaledToWidth(self.width*self.image_pen_width)) def draw_line_to(self, end_point): painter = QPainter(self.image) painter.setPen(QPen(Qt.white if self.scribbling == 1 else Qt.black, self.pen_width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.last_point/5, end_point/5) self.update() self.last_point = QPoint(end_point)
def convert(self, event): node = event.config.node buff = "" if str(node.dataType()).find("video") != -1: if VIDEO_API_EXISTS: try: md = video.VideoDecoder(node) if event.config.frames == 1: img = md.thumbnailAtPercent(event.config.percent, event.config.size) else: img = QImage(event.config.size * event.config.frames / 2, event.config.size * 2, 4) img.fill(0) painter = QPainter(img) for y in range(0, 2): try: for x in range(1, event.config.frames / 2 + 1): try: frame = md.thumbnailAtPercent( (x + ((event.config.frames / 2) * y)) * (100 / event.config.frames), event.config.size, ) painter.drawImage((x - 1) * event.config.size, y * event.config.size, frame) except RuntimeError, e: raise e except RuntimeError: break painter.end() self.emit(SIGNAL("scaledFinished"), event.config, img) return except: pass self.emit(SIGNAL("scaledFinished"), event.config, None) return img = QImage() load = None buff = "" if str(node.dataType()).find("jpeg") != -1 and node.size() < self.imageMaximumSize: try: buff = self.jpegInternalThumbnail(node) if buff: load = img.loadFromData(buff, "jpeg") if load == False: buff = "" except IOError: buff = "" if not len(buff) and node.size() < self.imageMaximumSize: try: f = node.open() buff = f.read() f.close() load = img.loadFromData(buff) except IOError: load = False if load: img = img.scaled(QSize(event.config.size, event.config.size), Qt.KeepAspectRatio, Qt.FastTransformation) self.emit(SIGNAL("scaledFinished"), event.config, img) return self.emit(SIGNAL("scaledFinished"), event.config, None) return
def animation(cfg, progress_fn=None): dpi = 96 l = cfg['layer'] w, h = cfg['img_size'] imgfile = cfg['tmp_imgfile'] layers = cfg['layers'] if 'layers' in cfg else [l.id()] extent = cfg['extent'] if 'extent' in cfg else l.extent() crs = cfg['crs'] if 'crs' in cfg else None dataset = l.currentDataSet() count = dataset.output_count() if 'time' in cfg: time_from, time_to = cfg['time'] else: time_from, time_to = dataset.output(0).time(), dataset.output( dataset.output_count() - 1).time() imgnum = 0 for i, o in enumerate(dataset.outputs()): if progress_fn: progress_fn(i, count) if o.time() < time_from or o.time() > time_to: continue l.current_output_time = o.time() mr = QgsMapRenderer() # setup map parameters mr.setExtent(extent) # only used when creating new composer map?? mr.setLayerSet(layers) mr.setOutputSize(QSize(w, h), dpi) # only used when creating new composer map if crs is not None: mr.setDestinationCrs(crs) mr.setProjectionsEnabled(True) c = prep_comp(cfg, mr, o.time()) # when using composition from template, match video's aspect ratio to paper size # by updating video's width (keeping the height) if cfg['layout']['type'] == 'file': aspect = c.paperWidth() / c.paperHeight() w = int(round(aspect * h)) image = QImage(QSize(w, h), QImage.Format_RGB32) image.fill(0) imagePainter = QPainter(image) sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight()) targetArea = QRectF(0, 0, w, h) c.render(imagePainter, targetArea, sourceArea) imagePainter.end() imgnum += 1 image.save(imgfile % imgnum) if progress_fn: progress_fn(count, count)
def _blendTile(self, stack_id, tile_nr): """ Blend all of the QImage layers of the patch specified by (stack_id, tile_nr) into a single QImage. """ qimg = None p = None for i, (visible, layerOpacity, layerImageSource) in enumerate(reversed(self._sims)): image_type = layerImageSource.image_type() if issubclass(image_type, QGraphicsItem): with self._cache: patch = self._cache.layer(stack_id, layerImageSource, tile_nr) if patch is not None: assert isinstance(patch, image_type), \ "This ImageSource is producing a type of image that is not consistent with it's declared image_type()" # This is a QGraphicsItem, so we don't blend it into the final tile. # (The ImageScene will just draw it on top of everything.) # But this is a convenient place to update the opacity/visible state. if patch.opacity() != layerOpacity or patch.isVisible( ) != visible: patch.setOpacity(layerOpacity) patch.setVisible(visible) patch.setZValue( i ) # The sims ("stacked image sources") are ordered from # top-to-bottom (see imagepump.py), but in Qt, # higher Z-values are shown on top. # Note that the current loop is iterating in reverse order. continue # No need to fetch non-visible image tiles. if not visible or layerOpacity == 0.0: continue with self._cache: patch = self._cache.layer(stack_id, layerImageSource, tile_nr) # patch might be a QGraphicsItem instead of QImage, # in which case it is handled separately, # not composited into the tile. if patch is not None: assert isinstance(patch, QImage), \ "Unknown tile layer type: {}. Expected QImage or QGraphicsItem".format(type(patch)) if qimg is None: qimg = QImage(self.tiling.imageRects[tile_nr].size(), QImage.Format_ARGB32_Premultiplied) qimg.fill(0xffffffff) # Use a hex constant instead. p = QPainter(qimg) p.setOpacity(layerOpacity) p.drawImage(0, 0, patch) if p is not None: p.end() return qimg
def saveSprites(folder, sprites): if sprites: height = max([s.height() for s, s2x in sprites.values()]) width = sum([s.width() for s, s2x in sprites.values()]) img = QImage(width, height, QImage.Format_ARGB32) img.fill(QColor(Qt.transparent)) img2x = QImage(width * 2, height * 2, QImage.Format_ARGB32) img2x.fill(QColor(Qt.transparent)) painter = QPainter(img) painter.begin(img) painter2x = QPainter(img2x) painter2x.begin(img2x) spritesheet = { NO_ICON: { "width": 0, "height": 0, "x": 0, "y": 0, "pixelRatio": 1 } } spritesheet2x = { NO_ICON: { "width": 0, "height": 0, "x": 0, "y": 0, "pixelRatio": 1 } } x = 0 for name, sprites in sprites.iteritems(): s, s2x = sprites painter.drawImage(x, 0, s) painter2x.drawImage(x * 2, 0, s2x) spritesheet[name] = { "width": s.width(), "height": s.height(), "x": x, "y": 0, "pixelRatio": 1 } spritesheet2x[name] = { "width": s2x.width(), "height": s2x.height(), "x": x * 2, "y": 0, "pixelRatio": 2 } x += s.width() painter.end() painter2x.end() img.save(os.path.join(folder, "spriteSheet.png")) img2x.save(os.path.join(folder, "*****@*****.**")) with open(os.path.join(folder, "spriteSheet.json"), 'w') as f: json.dump(spritesheet, f) with open(os.path.join(folder, "*****@*****.**"), 'w') as f: json.dump(spritesheet2x, f)
def saveExtra(self, picture, file_name, file_format): rect = picture.boundingRect() pix = QImage(rect.size(), QImage.Format_ARGB32) pix.fill(QColor(0, 0, 0, 0).rgba()) paint = QPainter() paint.begin(pix) paint.drawPicture(rect.topLeft()*-1, picture) paint.end() pix.save(file_name, file_format)
def paintEvent(self, event): super(DetailedProgress, self).paintEvent(event) if not self._current_progress: return painter = QPainter(self) width = self.width() height = self.height() aspect_ratio = float(width) / height nr_realizations = max([iens for iens, _, _ in self._current_progress]) + 1 fm_size = max( [len(progress) for _, progress, _ in self._current_progress]) self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio)) self.grid_width = math.ceil(self.grid_height * aspect_ratio) sub_grid_size = math.ceil(math.sqrt(fm_size)) cell_height = height / self.grid_height cell_width = width / self.grid_width foreground_image = QImage(self.grid_width * sub_grid_size, self.grid_height * sub_grid_size, QImage.Format_ARGB32) foreground_image.fill(QColor(0, 0, 0, 0)) for index, (iens, progress, _) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) self.draw_window(x * sub_grid_size, y * sub_grid_size, progress, foreground_image) painter.drawImage(self.contentsRect(), foreground_image) for index, (iens, progress, state) in enumerate(self._current_progress): y = int(iens / self.grid_width) x = int(iens - (y * self.grid_width)) painter.setPen(QColor(80, 80, 80)) painter.drawText(x * cell_width, y * cell_height, cell_width, cell_height, Qt.AlignHCenter | Qt.AlignVCenter, str(iens)) if iens == self.selected_realization: pen = QPen(QColor(240, 240, 240)) elif (self.has_realization_failed(progress)): pen = QPen(QColor(*self.state_colors['Failure'])) elif (state == JobStatusType.JOB_QUEUE_RUNNING): pen = QPen(QColor(*self.state_colors['Running'])) else: pen = QPen(QColor(80, 80, 80)) thickness = 4 pen.setWidth(thickness) painter.setPen(pen) painter.drawRect((x * cell_width) + (thickness / 2), (y * cell_height) + (thickness / 2), cell_width - (thickness - 1), cell_height - (thickness - 1))
def animation(cfg, progress_fn=None): dpi = 96 l = cfg['layer'] w,h = cfg['img_size'] imgfile = cfg['tmp_imgfile'] layers = cfg['layers'] if 'layers' in cfg else [l.id()] extent = cfg['extent'] if 'extent' in cfg else l.extent() crs = cfg['crs'] if 'crs' in cfg else None dataset = l.currentDataSet() count = dataset.output_count() if 'time' in cfg: time_from, time_to = cfg['time'] else: time_from, time_to = dataset.output(0).time(), dataset.output(dataset.output_count()-1).time() imgnum = 0 for i,o in enumerate(dataset.outputs()): if progress_fn: progress_fn(i, count) if o.time() < time_from or o.time() > time_to: continue l.current_output_time = o.time() mr = QgsMapRenderer() # setup map parameters mr.setExtent(extent) # only used when creating new composer map?? mr.setLayerSet(layers) mr.setOutputSize(QSize(w,h), dpi) # only used when creating new composer map if crs is not None: mr.setDestinationCrs(crs) mr.setProjectionsEnabled(True) c = prep_comp(cfg, mr, o.time()) # when using composition from template, match video's aspect ratio to paper size # by updating video's width (keeping the height) if cfg['layout']['type'] == 'file': aspect = c.paperWidth() / c.paperHeight() w = int(round(aspect * h)) image = QImage(QSize(w, h), QImage.Format_RGB32) image.fill(0) imagePainter = QPainter(image) sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight()) targetArea = QRectF(0, 0, w, h) c.render(imagePainter, targetArea, sourceArea) imagePainter.end() imgnum += 1 image.save(imgfile % imgnum) if progress_fn: progress_fn(count, count)
class DMXOverview(QWidget): def __init__(self, parent=None): super(QWidget, self).__init__(parent) self.setAttribute(Qt.WA_StaticContents) self.parent = parent self.width = 512 self.height = 32 self.pen_width = 1 self.image = QImage(QSize(self.width, self.height), QImage.Format_RGB32) self.setMaximumSize(self.width, self.height) self.setMinimumSize(self.width, self.height) self.last_point = QPoint() self.clear_image() self.white_pen = QPen(Qt.white, 1) self.black_pen = QPen(Qt.black, 1) def draw_frame(self, frame): painter = QPainter(self.image) for line, value in enumerate(frame): self.draw_line(line, value, painter) self.update() def draw_line(self, line, value, painter=None, update=False): if painter == None: painter = QPainter(self.image) painter.setPen(Qt.black) painter.drawLine(QPoint(line, 31 - value // 8), QPoint(line, 31)) painter.setPen(Qt.white) painter.drawLine(QPoint(line, 0), QPoint(line, 31 - value // 8)) if update: self.update() def fill_image(self, color): self.image.fill(color) self.update() def clear_image(self): self.image.fill(Qt.white) self.update() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: line = event.pos().x() self.parent.address_table.verticalScrollBar().setSliderPosition( line) def paintEvent(self, event): painter = QPainter(self) painter.drawImage(event.rect(), self.image)
def preview(request, layer_slug): """Home page for layers. :param request: The web request. :param layer_slug: The layer """ layer = get_object_or_404(Layer, slug=layer_slug) layer_path = os.path.join( settings.MEDIA_ROOT, 'layers', layer.slug, 'raw') map_layer = QgsVectorLayer(layer_path, layer.name, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(map_layer) layer_uri = tempfile.NamedTemporaryFile( suffix='.png', prefix='inasafe-web-', dir='/tmp/').name # create image image = QImage(QSize(100, 100), QImage.Format_ARGB32_Premultiplied) # set image's background color color = QColor(255, 255, 255) image.fill(color.rgb()) # create painter p = QPainter() p.begin(image) p.setRenderHint(QPainter.Antialiasing) renderer = QgsMapRenderer() # set layer set layers = [map_layer.id()] # add ID of every layer renderer.setLayerSet(layers) # set extent rect = QgsRectangle(renderer.fullExtent()) rect.scale(1.1) renderer.setExtent(rect) # set output size renderer.setOutputSize(image.size(), image.logicalDpiX()) # do the rendering renderer.render(p) p.end() # clean up registry_list = qgis_layers() QgsMapLayerRegistry.instance().removeMapLayer(map_layer.id()) print registry_list # save image image.save(layer_uri, 'png') with open(layer_uri, 'rb') as f: response = HttpResponse(f.read(), content_type='png') os.remove(layer_uri) return response
def saveExtra(self, picture, file_name, file_format): rect = picture.boundingRect() pix = QImage(rect.size(), QImage.Format_ARGB32) pix.fill(QColor(0, 0, 0, 0).rgba()) paint = QPainter() paint.begin(pix) paint.drawPicture(rect.topLeft() * -1, picture) paint.end() pix.save(file_name, file_format)
class ScribbleArea(QWidget): """ this scales the image but it's not good, too many refreshes really mess it up!!! """ def __init__(self, w, h, parent=None): super(ScribbleArea, self).__init__(parent) self.setAttribute(Qt.WA_StaticContents) self.scribbling = False self.width = w self.height = h self.image_pen_width = 5 self.pen_width = 1 self.pen_color = Qt.white self.image = QImage(QSize(w, h), QImage.Format_RGB32) self.setMaximumSize(w * self.image_pen_width, w * self.image_pen_width) self.setMinimumSize(w * self.image_pen_width, h * self.image_pen_width) self.last_point = QPoint() self.clear_image() def clear_image(self): self.image.fill(qRgb(0, 0, 0)) self.update() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.last_point = event.pos() self.scribbling = True def mouseMoveEvent(self, event): if (event.buttons() & Qt.LeftButton) and self.scribbling: self.draw_line_to(event.pos()) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton and self.scribbling: self.draw_line_to(event.pos()) self.scribbling = False def paintEvent(self, event): painter = QPainter(self) painter.drawImage( event.rect(), self.image.scaledToWidth(self.width * self.image_pen_width)) def draw_line_to(self, end_point): painter = QPainter(self.image) painter.setPen( QPen(self.pen_color, self.pen_width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.last_point / 5, end_point / 5) self.update() self.last_point = QPoint(end_point)
def create_qimage(self): total_width = 0 images = [] while total_width < self._width: w = min(self._width - total_width, 2 ** 15) image = QImage(w, self._height, QImage.Format_ARGB32) image.fill(QColor(235, 235, 235, 255)) total_width += w images.append(image) return images
def plotImage(self, width, height, image_format = QImage.Format_ARGB32_Premultiplied, _plotting_object = None): """Plots the data specified in the current input file as an image with the specified width and height, and with an optionally specified image format. Returns the image produced.""" image = QImage(width, height, image_format) image.fill(QColor(0, 0, 0, 0)) return self._plot(width, height, image, _plotting_object)[0]
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue): print perpAxisLabel, perpAxisValue img = QImage(width, height, QImage.Format_ARGB32) img.fill(0) p = QPainter(img) p.setPen(QColor(255, 255, 255)) p.setBrush(QBrush(QColor(255, 255, 255))) def arrow(p, From, To, label): p.drawLine(From, To) p.drawText(To, label) offset = 10 arrow(p, QPoint(offset, offset), QPoint(offset, height - offset), axisLabels[1]) arrow(p, QPoint(offset, offset), QPoint(width - offset, offset), axisLabels[0]) p.drawText(2 * offset, 2 * offset, "%s=%d" % (perpAxisLabel, perpAxisValue)) fm = p.fontMetrics() size = fm.size(Qt.TextSingleLine, "updown") p.drawText(numpy.random.randint(offset, width - offset - size.width()), numpy.random.randint(offset, height - offset - size.height()), "updown") dots = [] numPixels = 0 while numPixels < 30: r = numpy.random.randint(1, 255) rx, ry = numpy.random.randint(offset, width - offset), numpy.random.randint( offset, height - offset) if img.pixel(rx, ry) != 0: continue p.setPen(QPen(QColor(r, r, r))) p.drawPoint(rx, ry) dots.append(((rx, ry), r)) numPixels += 1 p.end() img.save('test.png') a = qimage2ndarray.rgb_view(img) a = a[:, :, 0].squeeze().swapaxes(0, 1) for (rx, ry), r in dots: assert QColor.fromRgba(img.pixel(rx, ry)).red( ) == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % ( QColor.fromRgba(img.pixel(rx, ry)).red(), r) assert (a[rx, ry] == r), "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r) return (a, dots)
def endDrawing(self, pos): has_moved = self._hasMoved # _hasMoved will change after calling moveTo if has_moved: self.moveTo(pos) else: assert(self.pos == pos) self.moveTo(QPointF(pos.x()+0.0001, pos.y()+0.0001)) # move a little # Qt seems to use strange rules for determining which pixels to set when rendering a brush stroke to a QImage. # We seem to get better results if we do the following: # 1) Slightly offset the source window because apparently there is a small shift in the data # 2) Render the scene to an image that is MUCH larger than the scene resolution (4x by 4x) # 3) Downsample each 4x4 patch from the large image back to a single pixel in the final image, # applying some threshold to determine if the final pixel is on or off. tempi = QImage(QSize(4*self.bb.width(), 4*self.bb.height()), QImage.Format_ARGB32_Premultiplied) #TODO: format tempi.fill(0) painter = QPainter(tempi) # Offset the source window. At first I thought the right offset was 0.5, because # that would seem to make sure points are rounded to pixel CENTERS, but # experimentation indicates that 0.25 is slightly better for some reason... source_rect = QRectF( QPointF(self.bb.x()+0.25, self.bb.y()+0.25), QSizeF(self.bb.width(), self.bb.height()) ) target_rect = QRectF( QPointF(0,0), QSizeF(4*self.bb.width(), 4*self.bb.height()) ) self.scene.render(painter, target=target_rect, source=source_rect) painter.end() # Now downsample: convert each 4x4 patch into a single pixel by summing and dividing ndarr = qimage2ndarray.rgb_view(tempi)[:,:,0].astype(int) ndarr = ndarr.reshape( (ndarr.shape[0],) + (ndarr.shape[1]//4,) + (4,) ) ndarr = ndarr.sum(axis=-1) ndarr = ndarr.transpose() ndarr = ndarr.reshape( (ndarr.shape[0],) + (ndarr.shape[1]//4,) + (4,) ) ndarr = ndarr.sum(axis=-1) ndarr = ndarr.transpose() ndarr //= 4*4 downsample_threshold = (7./16)*255 labels = numpy.where(ndarr>=downsample_threshold, numpy.uint8(self.drawnNumber), numpy.uint8(0)) labels = labels.swapaxes(0,1) assert labels.shape[0] == self.bb.width() assert labels.shape[1] == self.bb.height() ## ## ensure that at least one pixel is label when the brush size is 1 ## ## this happens when the user just clicked without moving ## in that case the lineitem will be so tiny, that it won't be rendered ## into a single pixel by the code above if not has_moved and self.brushSize <= 1 and numpy.count_nonzero(labels) == 0: labels[labels.shape[0]//2, labels.shape[1]//2] = self.drawnNumber self.brushStrokeAvailable.emit(QPointF(self.bb.x(), self.bb.y()), labels)
def renderScene( self, s, exportFilename=None): img = QImage(310,290,QImage.Format_ARGB32_Premultiplied) img.fill(0) p = QPainter(img) s.render(p) s.joinRendering() s.render(p) p.end() if exportFilename is not None: img.save(exportFilename) return byte_view(img)
def updateMask(control_image_path, rendered_image_path, mask_image_path): control_image = imageFromPath(control_image_path) if not control_image: error('Could not read control image {}'.format(control_image_path)) rendered_image = imageFromPath(rendered_image_path) if not rendered_image: error('Could not read rendered image {}'.format(rendered_image_path)) if not rendered_image.width() == control_image.width() or not rendered_image.height() == control_image.height(): print ('Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(control_image.width(), control_image.height(), rendered_image.width(), rendered_image.height())) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) #read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): print 'Mask image does not exist, creating {}'.format(mask_image_path) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) #loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 for y in xrange(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) for x in xrange(max_width): currentTolerance = qRed(struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: #ignore pixel continue expected_rgb = struct.unpack('I', control_scanline[x * 4:x * 4 + 4])[0] rendered_rgb = struct.unpack('I', rendered_scanline[x * 4:x * 4 + 4])[0] difference = colorDiff(expected_rgb, rendered_rgb) if difference > currentTolerance: #update mask image mask_image.setPixel(x, y, qRgb(difference, difference, difference)) mismatch_count += 1 if mismatch_count: #update mask mask_image.save(mask_image_path, "png") print 'Updated {} pixels in {}'.format(mismatch_count, mask_image_path) else: print 'No mismatches in {}'.format(mask_image_path)
def renderScene(self, s, exportFilename=None): img = QImage(310, 290, QImage.Format_ARGB32_Premultiplied) img.fill(0) p = QPainter(img) s.render(p) s.joinRendering() s.render(p) p.end() if exportFilename is not None: img.save(exportFilename) return byte_view(img)
def save_layer_as_image(layer, extent, path_to_file, max_resolution='1024', image_type = 'tif'): """ Select and save the currently visible extent to a .tif file :param width: image width :type width: int :param height: image height :type height: int :param name: name of the created file :type name: str :return: :rtype: """ # calculate the extents width and height width = extent.width() height = extent.height() # calculate the missing value (width or height) of the output file, based on the extent if width >= height: height_as_dec = max_resolution / width * height width = max_resolution height = int(height_as_dec) else: width_as_dec = max_resolution / height * width width = int(width_as_dec) height = max_resolution # append the resolution to the filename and call the save method filename=layer.name() if filename.startswith("WMS_"): filename=filename.replace("WMS_","") else: resolution_prefix = '{}_{}-'.format(width, height) filename = resolution_prefix + layer.name() img = QImage(QSize(width, height), QImage.Format_ARGB32_Premultiplied) color = QColor(187, 187, 187, 0) img.fill(color.rgba()) leonardo = QPainter() leonardo.begin(img) leonardo.setRenderHint(QPainter.Antialiasing) renderer = QgsMapRenderer() lst = [layer.id()] renderer.setLayerSet(lst) renderer.setExtent(extent) renderer.setOutputSize(img.size(), img.logicalDpiX()) renderer.render(leonardo) leonardo.end() filename += '.{}'.format(image_type) out_path = os.path.join(path_to_file, filename) if img.save(out_path, image_type): return out_path
def endDrawing(self, pos): self.moveTo(pos) self.growBoundingBox() tempi = QImage(QSize(self.bb.width(), self.bb.height()), QImage.Format_ARGB32_Premultiplied) #TODO: format tempi.fill(0) painter = QPainter(tempi) self.scene.render(painter, QRectF(QPointF(0,0), self.bb.size()), self.bb) return (self.bb.left(), self.bb.top(), tempi) #TODO: hackish, probably return a class ??
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue): print perpAxisLabel, perpAxisValue img = QImage(width, height, QImage.Format_ARGB32) img.fill(0) p = QPainter(img) p.setPen(QColor(255, 255, 255)) p.setBrush(QBrush(QColor(255, 255, 255))) def arrow(p, From, To, label): p.drawLine(From, To) p.drawText(To, label) offset = 10 arrow(p, QPoint(offset, offset), QPoint(offset, height - offset), axisLabels[1]) arrow(p, QPoint(offset, offset), QPoint(width - offset, offset), axisLabels[0]) p.drawText(2 * offset, 2 * offset, "%s=%d" % (perpAxisLabel, perpAxisValue)) fm = p.fontMetrics() size = fm.size(Qt.TextSingleLine, "updown") p.drawText( numpy.random.randint(offset, width - offset - size.width()), numpy.random.randint(offset, height - offset - size.height()), "updown", ) dots = [] numPixels = 0 while numPixels < 30: r = numpy.random.randint(1, 255) rx, ry = numpy.random.randint(offset, width - offset), numpy.random.randint(offset, height - offset) if img.pixel(rx, ry) != 0: continue p.setPen(QPen(QColor(r, r, r))) p.drawPoint(rx, ry) dots.append(((rx, ry), r)) numPixels += 1 p.end() img.save("test.png") a = qimage2ndarray.rgb_view(img) a = a[:, :, 0].squeeze().swapaxes(0, 1) for (rx, ry), r in dots: assert QColor.fromRgba(img.pixel(rx, ry)).red() == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % ( QColor.fromRgba(img.pixel(rx, ry)).red(), r, ) assert a[rx, ry] == r, "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r) return (a, dots)
def makeImage(dow, tod): layer = qgis.utils.iface.activeLayer() renderer = layer.rendererV2() renderer.setClassAttribute("-predicted_pickup_" + str(dow) + "_" + str(tod)) #http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/composer.html # create image img = QImage(QSize(800, 1000), QImage.Format_ARGB32_Premultiplied) # set image's background color color = QColor(255, 255, 255) img.fill(color.rgb()) # create painter p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing) render = QgsMapRenderer() # set layer set layers_to_draw = [] for l in iface.mapCanvas().layers(): if l.name() in ['grid', 'nyc_projected']: layers_to_draw.append(l.id()) #lst = [layer.id()] lst = layers_to_draw # add ID of every layer render.setLayerSet(lst) # set extent rect = QgsRectangle(render.fullExtent()) rect.scale(1.1) render.setExtent(rect) # set output size render.setOutputSize(img.size(), img.logicalDpiX()) # do the rendering render.render(p) p.end() # create file path imPath = '/Users/danil/Documents/GitHub/dmc/notebooks/workshop-1/-screenshots/' imName = str(dow) + "_" + str(tod) # save image img.save(imPath + imName + '.png', "png")
def _blendTile( self, stack_id, tile_nr): """ Blend all of the QImage layers of the patch specified by (stack_id, tile_nr) into a single QImage. """ qimg = None p = None for i, (visible, layerOpacity, layerImageSource) in enumerate(reversed(self._sims)): image_type = layerImageSource.image_type() if issubclass(image_type, QGraphicsItem): with self._cache: patch = self._cache.layer(stack_id, layerImageSource, tile_nr ) if patch is not None: assert isinstance(patch, image_type), \ "This ImageSource is producing a type of image that is not consistent with it's declared image_type()" # This is a QGraphicsItem, so we don't blend it into the final tile. # (The ImageScene will just draw it on top of everything.) # But this is a convenient place to update the opacity/visible state. if patch.opacity() != layerOpacity or patch.isVisible() != visible: patch.setOpacity(layerOpacity) patch.setVisible(visible) patch.setZValue(i) # The sims ("stacked image sources") are ordered from # top-to-bottom (see imagepump.py), but in Qt, # higher Z-values are shown on top. # Note that the current loop is iterating in reverse order. continue # No need to fetch non-visible image tiles. if not visible or layerOpacity == 0.0: continue with self._cache: patch = self._cache.layer(stack_id, layerImageSource, tile_nr ) # patch might be a QGraphicsItem instead of QImage, # in which case it is handled separately, # not composited into the tile. if patch is not None: assert isinstance(patch, QImage), \ "Unknown tile layer type: {}. Expected QImage or QGraphicsItem".format(type(patch)) if qimg is None: qimg = QImage(self.tiling.imageRects[tile_nr].size(), QImage.Format_ARGB32_Premultiplied) qimg.fill(0xffffffff) # Use a hex constant instead. p = QPainter(qimg) p.setOpacity(layerOpacity) p.drawImage(0,0, patch) if p is not None: p.end() return qimg
def Save(self): fileName = unicode(QFileDialog.getSaveFileName(directory="graph.png", filter="*.png")) if fileName == '': return scene = self.ui.graph.scene() scene.clearSelection() scene.setSceneRect(scene.itemsBoundingRect()) img = QImage(scene.sceneRect().size().toSize(), QImage.Format_ARGB32) img.fill(Qt.transparent) ptr = QPainter(img) self.ui.graph.scene().render(ptr) ptr.end() img.save(fileName)
def wait(self): array_data = self._arrayreq.wait() rectf = self.rectf if array_data.handedness_switched: # array_data should be of type slicingtools.ProjectedArray rectf = QRectF(rectf.height(), rectf.width()) from PyQt4.QtGui import QPainter img = QImage( QSize( self.rectf.width(), self.rectf.height() ), QImage.Format_ARGB32_Premultiplied) img.fill(0xffffffff) p = QPainter(img) p.drawImage(0,0, img) DummyItem(self.rectf).paint(p, None) return img
def convert_pic_umi(filename, out_file): data = ConstBitStream(filename=filename) magic = data.read("bytes:4") size = data.read("uintle:32") ew = data.read("uintle:16") eh = data.read("uintle:16") width = data.read("uintle:16") height = data.read("uintle:16") unk1 = data.read("uintle:32") chunks = data.read("uintle:32") image = QImage(width, height, QImage.Format_ARGB32) image.fill(0) painter = QPainter(image) for i in range(chunks): version = data.read("uintle:32") x = data.read("uintle:16") y = data.read("uintle:16") w = data.read("uintle:16") h = data.read("uintle:16") offset = data.read("uintle:32") size = data.read("uintle:32") # if not i == 1: # continue print w, h, size, offset temp_pos = data.bytepos data.bytepos = offset chunk = data.read(size * 8) data.bytepos = temp_pos chunk = decompress_umi(chunk) chunk = adjust_scanline(chunk, w, h) dump_to_file(chunk) chunk = QImage(chunk, w, h, QImage.Format_ARGB32) chunk.fill(0) # chunk.save("test.bmp") painter.drawImage(QRectF(x, y, w, h), chunk, QRectF((chunk.rect()))) # break painter.end() image.save(out_file) ################################################################################
def rasterize_svg(self, elem, width=0, height=0, format='PNG'): view_box = elem.get('viewBox', elem.get('viewbox', None)) sizes = None logger = self.oeb.logger if view_box is not None: try: box = [ float(x) for x in filter(None, re.split('[, ]', view_box)) ] sizes = [box[2] - box[0], box[3] - box[1]] except (TypeError, ValueError, IndexError): logger.warn( 'SVG image has invalid viewBox="%s", ignoring the viewBox' % view_box) else: for image in elem.xpath( 'descendant::*[local-name()="image" and ' '@height and contains(@height, "%")]'): logger.info( 'Found SVG image height in %, trying to convert...') try: h = float(image.get('height').replace('%', '')) / 100. image.set('height', str(h * sizes[1])) except: logger.exception( 'Failed to convert percentage height:', image.get('height')) data = QByteArray(xml2str(elem, with_tail=False)) svg = QSvgRenderer(data) size = svg.defaultSize() if size.width() == 100 and size.height() == 100 and sizes: size.setWidth(sizes[0]) size.setHeight(sizes[1]) if width or height: size.scale(width, height, Qt.KeepAspectRatio) logger.info('Rasterizing %r to %dx%d' % (elem, size.width(), size.height())) image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(QColor("white").rgb()) painter = QPainter(image) svg.render(painter) painter.end() array = QByteArray() buffer = QBuffer(array) buffer.open(QIODevice.WriteOnly) image.save(buffer, format) return str(array)