// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "graphics/ImageCrop.h" #include #include #include #include #include #include #include #include ImageCrop::ImageCrop(QObject *parent) : QObject(parent) { } QString ImageCrop::writableImagePath(const QString &fileName) const { const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir().mkpath(dir); // A constant name would rewrite the same file behind the same URL, which // stays pinned in the QML image cache, and the avatar-exchange dedup hands // an unchanged path the same sha - peers would never see a second crop. // A fresh name on every crop busts both. const QFileInfo file(fileName); const QString unique = file.completeBaseName() + QLatin1Char('-') + QString::number(QRandomGenerator::global()->generate64(), 16) + QLatin1Char('.') + file.suffix(); return dir + QLatin1Char('/') + unique; } bool ImageCrop::cropToFile(const QString &sourcePath, const QRectF &srcRect, int targetWidth, int targetHeight, const QString &outPath) const { // A file dialog reports a file:// URL, and old settings entries started that // way too; QImageReader wants a plain path. QString path = sourcePath; if (path.startsWith(QLatin1String("file://"))) path = QUrl(path).toLocalFile(); QImageReader reader(path); // A phone picture is often sideways in the file and right side up on disk; // the EXIF rotation has to be applied before the rectangle makes sense. reader.setAutoTransform(true); const QImage whole = reader.read(); if (whole.isNull()) return false; // A rectangle given in a 2026 resize of the file the clip intended - an // edge landing half a pixel out should not silently blank the output. const QRect source = srcRect.toAlignedRect().intersected(whole.rect()); if (source.isEmpty()) return false; const QImage picked = source == whole.rect() ? whole : whole.copy(source); QImage result = picked; if (targetWidth > 0 && targetHeight > 0 && (result.width() != targetWidth || result.height() != targetHeight)) { result = result.scaled(targetWidth, targetHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } return result.save(outPath); }