QT使用QPainter加水印
加水印的代码
//为QPixmap添加水印
void MainWindow::addMask(QPixmap& pm, const QString& text)
{
QPainter painter(&pm);
int fontSize = 25, spacing = 10;
QFont font("微软雅黑", fontSize, QFont::Thin);
font.setLetterSpacing(QFont::AbsoluteSpacing, spacing);
painter.setFont(font);
painter.setPen(QColor(150, 150, 150));
painter.translate(pm.width() / 2, -pm.width() / 2);//调整位置
painter.rotate(45);
int squareEdgeSize = pm.width() * sin(45.0) + pm.height() * sin(45.0);//对角线长度
int hCount = squareEdgeSize / ((fontSize + spacing) * (text.size() + 1)) + 1;
int x = squareEdgeSize / hCount + (fontSize + spacing) * 3;
int y = x / 2;
for (int i = 0; i < hCount; i++)
{
for (int j = 0; j < hCount * 2; j++)
{
painter.drawText(x * i, y * j,text);
}
}
}
//给某个路径的图片添加水印
void MainWindow::addMaskByPath(QString& imgPath, const QString& text)
{
QFileInfo newPicture(imgPath);
QPixmap qpm = FaceIdentityUtils::readImage(imgPath);
MainWindow::addMask(qpm, text);
QFile file(imgPath);
file.open(QIODevice::WriteOnly);
qpm.save(&file, "JPEG");
file.close();
}