Krita Source Code Documentation
Loading...
Searching...
No Matches
KisReferenceImage.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2017 Boudewijn Rempt <boud@valdyas.org>
3 *
4 * SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7#include "KisReferenceImage.h"
8#include "KoColorProfile.h"
10
11#include <QtMath>
12#include <QImage>
13#include <QMessageBox>
14#include <QPainter>
15#include <QApplication>
16#include <QClipboard>
17#include <QSharedData>
18#include <QFileInfo>
19#include <QImageReader>
20#include <QUrl>
21
22#include <QColorSpace>
23
24#include <kundo2command.h>
25#include <KoStore.h>
26#include <KoStoreDevice.h>
27#include <krita_utils.h>
29#include <kis_dom_utils.h>
30#include <SvgUtil.h>
33
34#include <KisDocument.h>
35#include <KisPart.h>
36
37#include "kis_clipboard.h"
38
39struct KisReferenceImage::Private : public QSharedData
40{
41 // Filename within .kra (for embedding)
43
44 // File on disk (for linking)
46
47 QImage image;
50
51 qreal saturation{1.0};
52 int id{-1};
53 bool embed{true};
54
55 bool loadFromFile() {
58 KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(QFileInfo(externalFilename).isReadable(), false);
59 {
60 QImageReader reader(externalFilename);
61 reader.setDecideFormatFromContent(true);
62 image = reader.read();
63
64 if (image.isNull()) {
65 reader.setAutoDetectImageFormat(true);
66 image = reader.read();
67 }
68
69 }
70
71 if (image.isNull()) {
73 }
74
75 if (image.isNull()) {
78 if (doc->image()->colorSpace()->colorModelId() == RGBAColorModelID) {
80 // Because we store as PNG, we'll need to convert to PQ here. One problem: we need to check when saving the reference images.
83 }
84 image = doc->image()->convertToQImage(doc->image()->bounds(), doc->image()->colorSpace()->profile());
85 image.setColorSpace(KoColorSpaceRegistry::instance()->QColorSpaceForProfile(doc->image()->colorSpace()->profile()));
86 } else {
87 image = doc->image()->convertToQImage(doc->image()->bounds(), 0);
88 }
89 }
91 }
92
93 // See https://bugs.kde.org/show_bug.cgi?id=416515 -- a jpeg image
94 // loaded into a qimage cannot be saved to png unless we explicitly
95 // convert the colorspace of the QImage
96#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
97 if (image.colorSpace().colorModel() != QColorSpace::ColorModel::Rgb || !image.colorSpace().isValid()) {
98 image.convertToColorSpace(QColorSpace(QColorSpace::SRgb));
99 }
100#else
101 image.convertToColorSpace(QColorSpace(QColorSpace::SRgb));
102#endif
103
104 return (!image.isNull());
105 }
106
107 bool loadFromQImage(const QImage &img) {
108 image = img;
109
110 return !image.isNull();
111 }
112
113 void updateCache() {
114 if (saturation < 1.0) {
116
117 if (saturation > 0.0) {
118 QPainter gc2(&cachedImage);
119 gc2.setOpacity(saturation);
120 gc2.drawImage(QPoint(), image);
121 }
122 } else {
123 // Need to convert ref image to ARGB to draw the zoom preview when color sampling
124 // Convert here to make sure already loaded ref images are converted
126 cachedImage.convertTo(QImage::Format_ARGB32);
127 }
128
130 }
131};
132
133
135 : KUndo2Command(kundo2_i18n("Set saturation"), parent)
136 , newSaturation(newSaturation)
137{
138 images.reserve(shapes.count());
139
140 Q_FOREACH(auto *shape, shapes) {
141 auto *reference = dynamic_cast<KisReferenceImage*>(shape);
143 images.append(reference);
144 }
145
146 Q_FOREACH(auto *image, images) {
147 oldSaturations.append(image->saturation());
148 }
149}
150
152{
153 auto saturationIterator = oldSaturations.begin();
154 Q_FOREACH(auto *image, images) {
155 image->setSaturation(*saturationIterator);
156 image->update();
157 saturationIterator++;
158 }
159}
160
162{
163 Q_FOREACH(auto *image, images) {
164 image->setSaturation(newSaturation);
165 image->update();
166 }
167}
168
174
176 : KoShape(rhs)
177 , d(rhs.d)
178{}
179
182
183KisReferenceImage * KisReferenceImage::fromFile(const QString &filename, const KisCoordinatesConverter &converter, QWidget *parent)
184{
185 KisReferenceImage *reference = new KisReferenceImage();
186 reference->d->externalFilename = filename;
187 bool ok = reference->d->loadFromFile();
188
189 if (ok) {
190 QRect r = QRect(QPoint(), reference->d->image.size());
191 QSizeF shapeSize = converter.imageToDocument(r).size();
192 reference->setSize(shapeSize);
193 } else {
194 delete reference;
195
196 if (parent) {
197 QMessageBox::critical(parent, i18nc("@title:window", "Krita"), i18n("Could not load %1.", filename));
198 }
199
200 return nullptr;
201 }
202
203 return reference;
204}
205
207{
208 KisImageSP clipImage = KisClipboard::instance()->clipImage(true);
209 return fromPaintDevice(clipImage->projection(), converter, nullptr);
210}
211
214{
215 if (!src) {
216 return nullptr;
217 }
218
219 auto *reference = new KisReferenceImage();
220#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
221 if (src->colorSpace()->colorModelId() == RGBAColorModelID) {
222 reference->d->image = src->convertToQImage(src->colorSpace()->profile());
223 reference->d->image.setColorSpace(KoColorSpaceRegistry::instance()->QColorSpaceForProfile(src->colorSpace()->profile()));
224 } else {
225 reference->d->image = src->convertToQImage(KoColorSpaceRegistry::instance()->p709SRGBProfile());
226 }
227#else
228 reference->d->image = src->convertToQImage(KoColorSpaceRegistry::instance()->p709SRGBProfile());
229#endif
230
231 QRect r = QRect(QPoint(), reference->d->image.size());
232 QSizeF size = converter.imageToDocument(r).size();
233 reference->setSize(size);
234
235 return reference;
236}
237
239{
240 KisReferenceImage *reference = new KisReferenceImage();
241 bool ok = reference->d->loadFromQImage(img);
242
243 if (ok) {
244 QRect r = QRect(QPoint(), reference->d->image.size());
245 QSizeF size = converter.imageToDocument(r).size();
246 reference->setSize(size);
247 } else {
248 delete reference;
249 reference = 0;
250 }
251
252 return reference;
253}
254
255void KisReferenceImage::paint(QPainter &gc) const
256{
257 if (!parent()) return;
258
259 gc.save();
260
261 QSizeF shapeSize = size();
262 // scale and rotation done by the user (excluding zoom)
263 QTransform transform = QTransform::fromScale(shapeSize.width() / d->image.width(), shapeSize.height() / d->image.height());
264
265 if (d->cachedImage.isNull()) {
266 // detach the data
267 const_cast<KisReferenceImage*>(this)->d->updateCache();
268 }
269
270 qreal scale;
271 // scale from the highDPI display
272 QTransform devicePixelRatioFTransform = QTransform::fromScale(gc.device()->devicePixelRatioF(), gc.device()->devicePixelRatioF());
273 // all three transformations: scale and rotation done by the user, scale from highDPI display, and zoom + rotation of the view
274 // order: zoom/rotation of the view; scale to high res; scale and rotation done by the user
275 QImage prescaled = d->mipmap.getClosestWithoutWorkaroundBorder(transform * devicePixelRatioFTransform * gc.transform(), &scale);
276 transform.scale(1.0 / scale, 1.0 / scale);
277
278 // Color conversion.
279 QImage *targetD = dynamic_cast<QImage*>(gc.device());
280#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
281 const bool getTargetCs = (targetD && targetD->colorSpace().colorModel() == QColorSpace::ColorModel::Rgb);
282
284 const KoColorProfile *sourceP = KoColorSpaceRegistry::instance()->profileForQColorSpace(d->image.colorSpace());
285 if (targetP != sourceP) {
287 dev->convertFromQImage(prescaled, sourceP);
289 prescaled = dev->convertToQImage(targetP);
290 if (getTargetCs) {
291 prescaled.setColorSpace(targetD->colorSpace());
292 } else {
293 prescaled.setColorSpace(QColorSpace(QColorSpace::SRgb));
294 }
295 }
296#endif
297
298 if (scale > 1.0) {
299 // enlarging should be done without smooth transformation
300 // so the user can see pixels just as they are painted
301 gc.setRenderHints(QPainter::Antialiasing);
302 } else {
303 gc.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
304 }
305 gc.setClipRect(QRectF(QPointF(), shapeSize), Qt::IntersectClip);
306 gc.setTransform(transform, true);
307 gc.drawImage(QPoint(), prescaled);
308
309 gc.restore();
310}
311
313{
314 d->saturation = saturation;
315 d->cachedImage = QImage();
316}
317
319{
320 return d->saturation;
321}
322
324{
325 KIS_SAFE_ASSERT_RECOVER_RETURN(embed || !d->externalFilename.isEmpty());
326 d->embed = embed;
327}
328
330{
331 return d->embed;
332}
333
335{
336 return !d->externalFilename.isEmpty();
337}
338
340{
341 return d->externalFilename;
342}
343
345{
346 return d->internalFilename;
347}
348
349
350void KisReferenceImage::setFilename(const QString &filename)
351{
352 d->externalFilename = filename;
353}
354
355QPointF KisReferenceImage::documentToPixel(const QPointF &docPoint)
356{
357 QSizeF shapeSize = size();
358 QTransform scale = QTransform::fromScale(d->image.width() / shapeSize.width(), d->image.height() / shapeSize.height());
359
360 QTransform transform = absoluteTransformation().inverted() * scale;
361 QPointF localPosition = docPoint * transform;
362
363 return localPosition;
364}
365
366
367QPoint KisReferenceImage::documentToPixelFloored(const QPointF &docPoint)
368{
369 QPointF localPoint = documentToPixel(docPoint);
370 return QPoint(qFloor(localPoint.x()), qFloor(localPoint.y()));
371}
372
374{
375 KoColor transparent;
376 transparent.setOpacity(0.0);
377 if (transparency() == 1.0) return transparent;
378
379 const QPoint localPosition = documentToPixelFloored(position);
380
381 if (d->cachedImage.isNull()) {
382 d->updateCache();
383 }
384
385#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
386 const KoColorProfile *profile = KoColorSpaceRegistry::instance()->profileForQColorSpace(d->image.colorSpace());
388#else
390#endif
391
392 KoColor c(cs);
393 QColor pixel = d->cachedImage.pixelColor(localPosition);
394 QVector<float> channels = {
395 static_cast<float>(pixel.blueF()),
396 static_cast<float>(pixel.greenF()),
397 static_cast<float>(pixel.redF()),
398 1.0f};
399 cs->fromNormalisedChannelsValue( c.data(),channels);
400
401 return c;
402}
403
404void KisReferenceImage::saveXml(QDomDocument &document, QDomElement &parentElement, int id)
405{
406 d->id = id;
407
408 QDomElement element = document.createElement("referenceimage");
409
410 if (d->embed) {
411 d->internalFilename = QString("reference_images/%1.png").arg(id);
412 }
413
414 const QString src = d->embed ? d->internalFilename : (QString("file://") + d->externalFilename);
415 element.setAttribute("src", src);
416
417 const QSizeF &shapeSize = size();
418 element.setAttribute("width", KisDomUtils::toString(shapeSize.width()));
419 element.setAttribute("height", KisDomUtils::toString(shapeSize.height()));
420 element.setAttribute("keepAspectRatio", keepAspectRatio() ? "true" : "false");
421 element.setAttribute("transform", SvgUtil::transformToString(transform()));
422
423 element.setAttribute("opacity", KisDomUtils::toString(1.0 - transparency()));
424 element.setAttribute("saturation", KisDomUtils::toString(d->saturation));
425
426 parentElement.appendChild(element);
427}
428
430{
431 auto *reference = new KisReferenceImage();
432
433 const QString &src = elem.attribute("src");
434
435 if (src.startsWith("file://")) {
436 reference->d->externalFilename = src.mid(7);
437 reference->d->embed = false;
438 } else {
439 reference->d->internalFilename = src;
440 reference->d->embed = true;
441 }
442
443 qreal width = KisDomUtils::toDouble(elem.attribute("width", "100"));
444 qreal height = KisDomUtils::toDouble(elem.attribute("height", "100"));
445 reference->setSize(QSizeF(width, height));
446 reference->setKeepAspectRatio(elem.attribute("keepAspectRatio", "true").toLower() == "true");
447
448 auto transform = SvgTransformParser(elem.attribute("transform")).transform();
449 reference->setTransformation(transform);
450
451 qreal opacity = KisDomUtils::toDouble(elem.attribute("opacity", "1"));
452 reference->setTransparency(1.0 - opacity);
453
454 qreal saturation = KisDomUtils::toDouble(elem.attribute("saturation", "1"));
455 reference->setSaturation(saturation);
456
457 return reference;
458}
459
461{
462 if (!d->embed) return true;
463
464 if (!store->open(d->internalFilename)) {
465 return false;
466 }
467
468 bool saved = false;
469
470 KoStoreDevice storeDev(store);
471 if (storeDev.open(QIODevice::WriteOnly)) {
472 saved = d->image.save(&storeDev, "PNG");
473 }
474
475 return store->close() && saved;
476}
477
479{
480 if (!d->embed) {
481 return d->loadFromFile();
482 }
483
484 if (!store->open(d->internalFilename)) {
485 return false;
486 }
487
488 KoStoreDevice storeDev(store);
489 if (!storeDev.open(QIODevice::ReadOnly)) {
490 return false;
491 }
492
493 if (!d->image.load(&storeDev, "PNG")) {
494 return false;
495 }
496
497 return store->close();
498}
499
501{
502 return d->image;
503}
504
506{
507 if (d->cachedImage.isNull()) d->updateCache();
508
509 return d->cachedImage;
510}
511
513{
514 return new KisReferenceImage(*this);
515}
const KoID Float32BitsColorDepthID("F32", ki18n("32-bit float/channel"))
const KoID Float16BitsColorDepthID("F16", ki18n("16-bit float/channel"))
const KoID Integer8BitsColorDepthID("U8", ki18n("8-bit integer/channel"))
const KoID Integer16BitsColorDepthID("U16", ki18n("16-bit integer/channel"))
const KoID RGBAColorModelID("RGBA", ki18n("RGB/Alpha"))
static KisClipboard * instance()
KisImageSP clipImage(bool showPopup, int overridePasteBehaviour=-1) const
_Private::Traits< T >::Result imageToDocument(const T &obj) const
KisImageSP image
bool openPath(const QString &path, OpenFlags flags=None)
openPath Open a Path
QImage convertToQImage(qint32 x1, qint32 y1, qint32 width, qint32 height, const KoColorProfile *profile)
const KoColorSpace * colorSpace() const
void convertImageColorSpace(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent, KoColorConversionTransformation::ConversionFlags conversionFlags)
KisPaintDeviceSP projection() const
QRect bounds() const override
QImage convertToQImage(const KoColorProfile *dstProfile, qint32 x, qint32 y, qint32 w, qint32 h, KoColorConversionTransformation::Intent renderingIntent=KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags=KoColorConversionTransformation::internalConversionFlags()) const
void convertFromQImage(const QImage &image, const KoColorProfile *profile, qint32 offsetX=0, qint32 offsetY=0)
void convertTo(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent=KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags=KoColorConversionTransformation::internalConversionFlags(), KUndo2Command *parentCommand=nullptr, KoUpdater *progressUpdater=nullptr)
static KisPart * instance()
Definition KisPart.cpp:131
void removeDocument(KisDocument *document, bool deleteDocument=true)
Definition KisPart.cpp:247
KisDocument * createTemporaryDocument() const
Definition KisPart.cpp:235
The KisReferenceImage class represents a single reference image.
bool saveImage(KoStore *store) const
bool loadImage(KoStore *store)
void paint(QPainter &gc) const override
Paint the shape fill The class extending this one is responsible for painting itself....
QString filename() const
static KisReferenceImage * fromFile(const QString &filename, const KisCoordinatesConverter &converter, QWidget *parent)
KoShape * cloneShape() const override
creates a deep copy of the shape or shape's subtree
void setFilename(const QString &filename)
QPointF documentToPixel(const QPointF &docPoint)
static KisReferenceImage * fromClipboard(const KisCoordinatesConverter &converter)
QPoint documentToPixelFloored(const QPointF &docPoint)
void setEmbed(bool embed)
KoColor getPixel(QPointF position)
static KisReferenceImage * fromQImage(const KisCoordinatesConverter &converter, const QImage &img)
void setSaturation(qreal saturation)
void saveXml(QDomDocument &document, QDomElement &parentElement, int id)
QString internalFile() const
static KisReferenceImage * fromPaintDevice(KisPaintDeviceSP src, const KisCoordinatesConverter &converter, QWidget *parent)
QSharedDataPointer< Private > d
static KisReferenceImage * fromXml(const QDomElement &elem)
virtual KoID colorModelId() const =0
virtual KoID colorDepthId() const =0
virtual void fromNormalisedChannelsValue(quint8 *pixel, const QVector< float > &values) const =0
virtual const KoColorProfile * profile() const =0
void setOpacity(quint8 alpha)
Definition KoColor.cpp:333
quint8 * data()
Definition KoColor.h:144
QString id() const
Definition KoID.cpp:63
virtual QSizeF size() const
Get the size of the shape in pt.
Definition KoShape.cpp:735
void setKeepAspectRatio(bool keepAspect)
Definition KoShape.cpp:865
KoShapeContainer * parent() const
Definition KoShape.cpp:860
QTransform absoluteTransformation() const
Definition KoShape.cpp:330
void scale(qreal sx, qreal sy)
Scale the shape using the zero-point which is the top-left corner.
Definition KoShape.cpp:210
bool keepAspectRatio() const
Definition KoShape.cpp:873
QTransform transform() const
return the current matrix that contains the rotation/scale/position of this shape
Definition KoShape.cpp:948
qreal transparency(bool recursive=false) const
Definition KoShape.cpp:645
virtual void setSize(const QSizeF &size)
Resize the shape.
Definition KoShape.cpp:249
QPointF position() const
Get the position of the shape in pt.
Definition KoShape.cpp:740
bool open(OpenMode m) override
bool close()
Definition KoStore.cpp:156
bool open(const QString &name)
Definition KoStore.cpp:109
QTransform transform() const
static QString transformToString(const QTransform &transform)
Converts specified transformation to a string.
Definition SvgUtil.cpp:104
#define KIS_SAFE_ASSERT_RECOVER_BREAK(cond)
Definition kis_assert.h:127
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129
#define KIS_SAFE_ASSERT_RECOVER_RETURN(cond)
Definition kis_assert.h:128
KUndo2MagicString kundo2_i18n(const char *text)
double toDouble(const QString &str, bool *ok=nullptr)
QString toString(const QString &value)
QImage convertQImageToGrayA(const QImage &image)
bool loadFromQImage(const QImage &img)
SetSaturationCommand(const QList< KoShape * > &images, qreal newSaturation, KUndo2Command *parent=0)
QVector< KisReferenceImage * > images
const KoColorSpace * colorSpace(const QString &colorModelId, const QString &colorDepthId, const KoColorProfile *profile)
static KoColorSpaceRegistry * instance()
const KoColorProfile * p709SRGBProfile() const
const KoColorSpace * rgb8(const QString &profileName=QString())
const KoColorProfile * profileForQColorSpace(const QColorSpace &space)
profileForQColorSpace Find a KoColorProfile that matches a given QColorSpace. This will use the QColo...
const KoColorProfile * p2020PQProfile() const