如何使用 QPainterPath 裁剪图像而不保存图像的其余部分 [英] How to crop an image using QPainterPath without saving rest of image

查看:80
本文介绍了如何使用 QPainterPath 裁剪图像而不保存图像的其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QPainterPath,我想裁剪一个 QPixmap 图像.这段代码对我有用,但我想使用 PyQt5 内置功能像没有numpy的面具

I have a QPainterPath and I want to crop an image which is QPixmap. This code worked for me but I want to use PyQt5 builtin functionality like mask without numpy

# read image as RGB and add alpha (transparency)
im = Image.open("frontal_1.jpg").convert("RGBA")

# convert to numpy (for convenience)
imArray = numpy.asarray(im)

# create mask
polygon = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]

maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)
mask = numpy.array(maskIm)
...
newIm = Image.fromarray(newImArray, "RGBA")
newIm.save("out.png")

推荐答案

一种可能的替换掩码的方法是使用 QPainter 的 setClipPath() 方法:

One possible way to replace mask is to use the setClipPath() method of QPainter:

from PyQt5 import QtCore, QtGui

if __name__ == '__main__':
    image = QtGui.QImage('input.png')
    output = QtGui.QImage(image.size(), QtGui.QImage.Format_ARGB32)
    output.fill(QtCore.Qt.transparent)
    painter = QtGui.QPainter(output)

    points = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]
    polygon = QtGui.QPolygonF([QtCore.QPointF(*point) for point in points])

    path = QtGui.QPainterPath()
    path.addPolygon(polygon)
    painter.setClipPath(path)
    painter.drawImage(QtCore.QPoint(), image)
    painter.end()
    output.save('out.png')

这篇关于如何使用 QPainterPath 裁剪图像而不保存图像的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆