1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
/*
* Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtScaledAvatarCache.h>
#include <QByteArray>
#include <QDir>
#include <QFileInfo>
#include <QImage>
#include <QImageReader>
#include <QPainter>
#include <QPixmap>
#include <Swiften/Base/Log.h>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtScaledAvatarCache::QtScaledAvatarCache(int size) : size(size) {
}
static QPixmap cropToBiggestCenteredSquare(const QPixmap& input) {
QPixmap squareCropped;
if (input.width() != input.height()) {
QRect centeredSquare;
if (input.width() > input.height()) {
int x = (input.width() - input.height()) / 2;
centeredSquare = QRect(x, 0, input.height(), input.height());
}
else {
int y = (input.height() - input.width()) / 2;
centeredSquare = QRect(0, y, input.width(), input.width());
}
squareCropped = input.copy(centeredSquare);
}
else {
squareCropped = input;
}
return squareCropped;
}
QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) {
QFileInfo avatarFile(path);
if (avatarFile.exists()) {
if (!avatarFile.dir().exists(QString::number(size))) {
if (!avatarFile.dir().mkdir(QString::number(size))) {
return path;
}
}
QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size)));
QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
if (!QFileInfo(targetFile).exists()) {
QPixmap avatarPixmap;
if (avatarPixmap.load(path)) {
QPixmap squaredAvatarPixmap = cropToBiggestCenteredSquare(avatarPixmap);
QPixmap maskedAvatar(squaredAvatarPixmap.size());
maskedAvatar.fill(QColor(0, 0, 0, 0));
QPainter maskPainter(&maskedAvatar);
maskPainter.setBrush(Qt::black);
maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize);
maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
maskPainter.drawPixmap(0, 0, squaredAvatarPixmap);
maskPainter.end();
if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
return path;
}
} else {
SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl;
}
}
return targetFile;
}
else {
return path;
}
}
}
|