PyQt QImage 边框半径与 for 循环
PyQt QImage Border Radius with for loop
我有 Rectangle PNG,我想处理这个图像,删除一些像素到边距并保存为 png 格式。
这是我想要的结尾;
普通图像(没有边距 - 边框半径):
这是我的代码;我尝试了一些但没有正常工作;
qimg = QImage(PNG_YOL)
qimg = qimg.convertToFormat(QImage.Format_ARGB32) # making png or will be there black pixels
p = QPainter()
p.begin(qimg)
w = qimg.width() - 1
h=qimg.height() -1
for x in range(int(maxx)):
dx = 1 # i changed this value to get what i want, it works but not very fine, i am looking better way
for y in range(int(maxy)):
if x == 0:
qimg.setPixel(x, y, Qt.transparent)
qimg.setPixel(w - x, y, Qt.transparent)
if x != 0 and y < int(h * 1 / x / dx):
qimg.setPixel(x, y, Qt.transparent)
qimg.setPixel(w - x, y, Qt.transparent)
if x != 0:
qimg.setPixel(x, int(h * 1 / x / dx), Qt.transparent)
qimg.setPixel(w - x, int(h * 1 / x / dx), Qt.transparent)
p.end()
qimg.save(PNG_YOL)
使用这段代码,我可以获得很好的结果,但我正在寻找更好的方法。
注意:我只想为左上角和右上角添加边距。
您可以将 QPainter 与 QPainterPath 一起使用,而不是过多地逐个像素地处理:
from PyQt5 import QtCore, QtGui
qin = QtGui.QImage("input.png")
qout = QtGui.QImage(qin.size(), qin.format())
qout.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(qout)
path = QtGui.QPainterPath()
radius = 20
r = qout.rect()
path.arcMoveTo(0, 0, radius, radius, 180)
path.arcTo(0, 0, radius, radius, 180, -90)
path.arcTo(r.width()-radius, 0, radius, radius, 90, -90)
path.lineTo(r.bottomRight())
path.lineTo(r.bottomLeft())
path.closeSubpath()
painter.setClipPath(path)
painter.drawImage(QtCore.QPoint(0, 0), qin)
painter.end()
qout.save("output.png")
我有 Rectangle PNG,我想处理这个图像,删除一些像素到边距并保存为 png 格式。
这是我想要的结尾;
普通图像(没有边距 - 边框半径):
这是我的代码;我尝试了一些但没有正常工作;
qimg = QImage(PNG_YOL)
qimg = qimg.convertToFormat(QImage.Format_ARGB32) # making png or will be there black pixels
p = QPainter()
p.begin(qimg)
w = qimg.width() - 1
h=qimg.height() -1
for x in range(int(maxx)):
dx = 1 # i changed this value to get what i want, it works but not very fine, i am looking better way
for y in range(int(maxy)):
if x == 0:
qimg.setPixel(x, y, Qt.transparent)
qimg.setPixel(w - x, y, Qt.transparent)
if x != 0 and y < int(h * 1 / x / dx):
qimg.setPixel(x, y, Qt.transparent)
qimg.setPixel(w - x, y, Qt.transparent)
if x != 0:
qimg.setPixel(x, int(h * 1 / x / dx), Qt.transparent)
qimg.setPixel(w - x, int(h * 1 / x / dx), Qt.transparent)
p.end()
qimg.save(PNG_YOL)
使用这段代码,我可以获得很好的结果,但我正在寻找更好的方法。
注意:我只想为左上角和右上角添加边距。
您可以将 QPainter 与 QPainterPath 一起使用,而不是过多地逐个像素地处理:
from PyQt5 import QtCore, QtGui
qin = QtGui.QImage("input.png")
qout = QtGui.QImage(qin.size(), qin.format())
qout.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(qout)
path = QtGui.QPainterPath()
radius = 20
r = qout.rect()
path.arcMoveTo(0, 0, radius, radius, 180)
path.arcTo(0, 0, radius, radius, 180, -90)
path.arcTo(r.width()-radius, 0, radius, radius, 90, -90)
path.lineTo(r.bottomRight())
path.lineTo(r.bottomLeft())
path.closeSubpath()
painter.setClipPath(path)
painter.drawImage(QtCore.QPoint(0, 0), qin)
painter.end()
qout.save("output.png")