python - 在 QImage 上绘制矩形而不显示它
问题描述
我想在 QImage 上方绘制矩形并将结果保存为 png。下面的最小示例应该这样做。
from PyQt5.QtGui import QImage, QColor, QPainter, QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Drawing Tutorial"
self.top = 150
self.left = 150
self.width = 500
self.height = 500
self.mypainter = MyPainter()
self.mypainter.create()
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
class MyPainter(QWidget):
def __init__(self):
super().__init__()
self.img = QImage(25, 25, QImage.Format_RGBA64)
self.color1 = QColor(255, 0, 0, 255)
self.color2 = QColor(0, 255, 0, 255)
self.color3 = QColor(0, 0, 255, 255)
self.boxes = (
(2, 2, 10, 10),
(5, 5, 4, 5),
(10, 10, 10, 7))
def create(self):
self.colors = (
self.color1,
self.color2,
self.color3)
for idx, box in enumerate(self.boxes):
self.color = self.colors[idx]
self.bndboxSize = box
self.repaint()
self.img.save("myImg.png")
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(self.rect(), self.img)
painter.setBrush(QBrush(self.color))
painter.drawRect(self.bndboxSize)
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
我所期望的
黑色背景也可以是透明的。
我得到了什么
这只是带有 alphachannel 的图像,如果您将鼠标悬停,您将获得链接
我得到了什么(调试模式)
我不知道如何获得想要的图像。
解决方案
如果要创建图像,则无需使用小部件,但必须使用 QPainter 在 QImage 上进行绘制。在 OP 的尝试中,它被绘制在 QWidget 上,并且 QImage 只有噪声。
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QColor, QGuiApplication, QImage, QPainter
def create_image():
img = QImage(25, 25, QImage.Format_RGBA64)
img.fill(Qt.black)
painter = QPainter(img)
colors = (QColor(255, 0, 0, 255), QColor(0, 255, 0, 255), QColor(0, 0, 255, 255))
boxes = (QRect(2, 2, 10, 10), QRect(5, 5, 4, 5), QRect(10, 10, 10, 7))
for color, box in zip(colors, boxes):
painter.fillRect(box, color)
painter.end()
return img
def main():
app = QGuiApplication([])
qimage = create_image()
qimage.save("myImg.png")
if __name__ == "__main__":
main()
输出:
推荐阅读
- sql - SQL(SQL/Oracle)使用序列从选择语句中插入值
- classification - 在分类中使用线性判别分析和 k 最近邻时,哪个更好?
- node.js - 在具有不同 publicPath 的 webpack 中两次注入相同的资产
- fortran - 在 Fortran 不好的做法中声明虚拟参数的大小(元素数量)
- python-3.x - 使用子进程从标准输出读取数据时出现意外的额外反斜杠
- python - 从两个多维 numpy 数组复制到另一个具有不同形状的数组
- go - Golang 序列化 go-radix Tree 到文件?
- javascript - setTimeout 回调执行后清除超时
- python - 'VoiceClient' 对象不能用 discord API/youtube_dl 调用
- python - Python authlib flask - 如何处理刷新令牌?