本文介绍了如何渲染QGraphicsScene的一部分并将其保存为图像文件PyQt5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我将加载的图像中的 QGraphicsPixmapItem
添加到 QGraphicsScene
.假设我将在场景中添加几个 QGraphicsPolygonItem
.我如何将场景的一部分渲染为全尺寸图像,其中多边形不在空白区域,并保存这个区域作为图像文件.强>
Suppose I have QGraphicsPixmapItem
from loaded image which is added to QGraphicsScene
. And suppose I'll add several QGraphicsPolygonItem
's on scene. How I can render a part of the scene as full-size image both with polygons that are not in blank area and save this area as image file.
class ImageView(QtWidgets.QGraphicsView):
def __init__(self, parent):
super(ImageView, self).__init__(parent)
self.setFocus()
self._zoom = 0
self._empty = True
self.scene = QtWidgets.QGraphicsScene(self)
self._image = QGraphicsPixmapItem()
self.scene.addItem(self._image)
self.setScene(self.scene)
# some other actions
foo()
def fitInView(self):
# custom fit in view and scaling
bar()
# some other methods
class MainWindow(QtWidgets.QWidget):
def __init__(self):
self.viewer = ImageView(self)
foo()
def _save_image(self):
# method that I need to implement
pass
推荐答案
未测试,但使用 QGraphicsScene::render
你应该能够做类似的事情......
Untested, but using QGraphicsScene::render
you should be able to do something like...
def _save_image(self):
# Get region of scene to capture from somewhere.
area = get_QRect_to_capture_from_somewhere()
# Create a QImage to render to and fix up a QPainter for it.
image = QImage(area.size(), QImage.Format_ARGB32_Premultiplied)
painter = QPainter(image)
# Render the region of interest to the QImage.
self.scene.render(painter, image.rect(), area)
painter.end()
# Save the image to a file.
image.save("capture.png")
这篇关于如何渲染QGraphicsScene的一部分并将其保存为图像文件PyQt5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!