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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667 | /* ============================================================
*
* This file is a part of digiKam project
* https://www.digikam.org
*
* Date : 2005-06-14
* Description : digiKam 8/16 bits image management API.
* Metadata operations.
*
* SPDX-FileCopyrightText: 2005-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
* SPDX-FileCopyrightText: 2006-2013 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* ============================================================ */
#include "dimg_p.h"
namespace Digikam
{
QByteArray DImg::getUniqueHash()
{
if (hasAttribute(QLatin1String("uniqueHash")))
{
return attribute(QLatin1String("uniqueHash")).toByteArray();
}
if (!hasAttribute(QLatin1String("originalFilePath")))
{
qCWarning(DIGIKAM_DIMG_LOG) << "DImg::getUniqueHash called without originalFilePath property set!";
return QByteArray();
}
QString filePath = attribute(QLatin1String("originalFilePath")).toString();
if (filePath.isEmpty())
{
return QByteArray();
}
FileReadLocker lock(filePath);
QScopedPointer<DMetadata> meta(new DMetadata(getMetadata()));
QByteArray ba = meta->getExifEncoded();
QByteArray hash = DImg::createUniqueHash(filePath, ba);
setAttribute(QLatin1String("uniqueHash"), hash);
return hash;
}
QByteArray DImg::getUniqueHash(const QString& filePath)
{
QScopedPointer<DMetadata> meta(new DMetadata(filePath));
QByteArray ba = meta->getExifEncoded();
return DImg::createUniqueHash(filePath, ba);
}
QByteArray DImg::getUniqueHashVersion(int version)
{
const QString uniqueHash(QString::fromLatin1("uniqueHashV%1").arg(version));
if (hasAttribute(uniqueHash))
{
return attribute(uniqueHash).toByteArray();
}
if (!hasAttribute(QLatin1String("originalFilePath")))
{
qCWarning(DIGIKAM_DIMG_LOG) << "DImg::getUniqueHashVersion called without "
"originalFilePath property set!";
return QByteArray();
}
QString filePath = attribute(QLatin1String("originalFilePath")).toString();
if (filePath.isEmpty())
{
return QByteArray();
}
FileReadLocker lock(filePath);
QByteArray hash = DImg::getUniqueHashVersion(filePath, version);
setAttribute(uniqueHash, hash);
return hash;
}
QByteArray DImg::getUniqueHashVersion(const QString& filePath, int version)
{
if (version == 2)
{
return DImg::createUniqueHashV2(filePath);
}
else if (version == 3)
{
return DImg::createUniqueHashV3(filePath);
}
qCWarning(DIGIKAM_DIMG_LOG) << "DImg::getUniqueHashVersion called with "
"unsupported version:" << version;
return QByteArray();
}
QByteArray DImg::createImageUniqueId()
{
NonDeterministicRandomData randomData(16);
QByteArray imageUUID = randomData.toHex();
imageUUID += getUniqueHashVersion(2);
return imageUUID;
}
void DImg::prepareMetadataToSave(const QString& intendedDestPath, const QString& destMimeType,
bool resetExifOrientationTag)
{
PrepareMetadataFlags flags = PrepareMetadataFlagsAll;
if (!resetExifOrientationTag)
{
flags &= ~ResetExifOrientationTag;
}
QUrl url = QUrl::fromLocalFile(originalFilePath());
prepareMetadataToSave(intendedDestPath, destMimeType, url.fileName(), flags);
}
void DImg::prepareMetadataToSave(const QString& intendedDestPath, const QString& destMimeType,
const QString& originalFileName, PrepareMetadataFlags flags)
{
if (isNull())
{
return;
}
// Get image Exif/IPTC data.
QScopedPointer<DMetadata> meta(new DMetadata(getMetadata()));
qCDebug(DIGIKAM_DIMG_LOG) << "Prepare Metadata to save for" << intendedDestPath;
if ((flags & RemoveOldMetadataPreviews) || (flags & CreateNewMetadataPreview))
{
// Clear IPTC preview
meta->removeIptcTag("Iptc.Application2.Preview");
meta->removeIptcTag("Iptc.Application2.PreviewFormat");
meta->removeIptcTag("Iptc.Application2.PreviewVersion");
// Clear Exif thumbnail
meta->removeExifThumbnail();
// Clear Tiff thumbnail
MetaEngine::MetaDataMap tiffThumbTags = meta->getExifTagsDataList(QStringList() << QLatin1String("SubImage1"));
for (MetaEngine::MetaDataMap::iterator it = tiffThumbTags.begin() ; it != tiffThumbTags.end() ; ++it)
{
meta->removeExifTag(it.key().toLatin1().constData());
}
// Clear Xmp preview from digiKam namespace
meta->removeXmpTag("Xmp.digiKam.Preview");
}
// Refuse preview creation for images with transparency
// as long as we have no format to support this. See bug 286127
if ((flags & CreateNewMetadataPreview) && !hasTransparentPixels())
{
const QSize standardPreviewSize(1280, 1280);
QSize previewSize = size();
// Scale to standard preview size. Only scale down, not up
if (width() > (uint)standardPreviewSize.width() && height() > (uint)standardPreviewSize.height())
{
previewSize.scale(standardPreviewSize, Qt::KeepAspectRatio);
}
// Only store a new preview if it is worth it - the original should be significantly larger than the preview
bool storeNewPreview = (2 * (uint)previewSize.width() <= width());
// Create the preview and thumb QImage
QImage preview;
QImage thumb;
{
if (!IccManager::isSRGB(*this))
{
DImg previewDImg;
if (previewSize.width() >= (int)width())
{
previewDImg = copy();
}
else
{
previewDImg = smoothScale(previewSize.width(),
previewSize.height(),
Qt::IgnoreAspectRatio);
}
IccManager manager(previewDImg);
manager.transformToSRGB();
preview = previewDImg.copyQImage();
}
else
{
// Ensure that preview is not upscaled
if (previewSize.width() >= (int)width())
{
preview = copyQImage();
}
else
{
preview = smoothScale(previewSize.width(),
previewSize.height(),
Qt::IgnoreAspectRatio).copyQImage();
}
}
thumb = preview.scaled(160, 120, Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
// Update IPTC preview.
// see bug #130525. a JPEG segment is limited to 64K. If the IPTC byte array is
// bigger than 64K during of image preview tag size, the target JPEG image will be
// broken. Note that IPTC image preview tag is limited to 256K!!!
// There is no limitation with TIFF and PNG about IPTC byte array size.
// So for a JPEG file, we don't store the IPTC preview.
if (
storeNewPreview &&
((destMimeType.toUpper() == QLatin1String("PNG")) ||
(destMimeType.toUpper() == QLatin1String("TIF")) ||
(destMimeType.toUpper() == QLatin1String("TIFF")))
)
{
// Non JPEG file, we update IPTC and XMP preview
meta->setItemPreview(preview);
}
if (
(destMimeType.toUpper() == QLatin1String("TIF")) ||
(destMimeType.toUpper() == QLatin1String("TIFF"))
)
{
// With TIFF file, we don't store JPEG thumbnail, we even need to erase it and store
// a thumbnail at a special location. See bug #211758
meta->setTiffThumbnail(thumb);
// Update Exif Image dimensions.
// Disable Exif.Photo.PixelX(Y)Dimension in TIFF files.
meta->setItemDimensions(size(), false);
}
else
{
// Update Exif thumbnail.
meta->setExifThumbnail(thumb);
// Update Exif Image dimensions.
meta->setItemDimensions(size());
}
}
// Update Exif Document Name tag with the original file name.
if (!originalFileName.isEmpty())
{
meta->setExifTagString("Exif.Image.DocumentName", originalFileName);
}
// Update Exif Orientation tag if necessary.
if (flags & ResetExifOrientationTag)
{
meta->setItemOrientation(DMetadata::ORIENTATION_NORMAL);
}
if (!m_priv->imageHistory.isEmpty())
{
DImageHistory forSaving(m_priv->imageHistory);
forSaving.adjustReferredImages();
QUrl url = QUrl::fromLocalFile(intendedDestPath);
QString filePath = url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile() + QLatin1Char('/');
QString fileName = url.fileName();
if (!filePath.isEmpty() && !fileName.isEmpty())
{
forSaving.purgePathFromReferredImages(filePath, fileName);
}
QString imageHistoryXml = forSaving.toXml();
meta->setItemHistory(imageHistoryXml);
}
if (flags & CreateNewImageHistoryUUID)
{
meta->setItemUniqueId(QString::fromUtf8(createImageUniqueId()));
}
// Store new Exif/IPTC/XMP data into image.
setMetadata(meta->data());
}
HistoryImageId DImg::createHistoryImageId(const QString& filePath, HistoryImageId::Type type)
{
QFileInfo fileInfo(filePath);
if (!fileInfo.exists())
{
return HistoryImageId();
}
QScopedPointer<DMetadata> metadata(new DMetadata(getMetadata()));
HistoryImageId id(metadata->getItemUniqueId());
QDateTime dt = metadata->getItemDateTime();
if (dt.isNull())
{
dt = creationDateFromFilesystem(fileInfo);
}
id.setCreationDate(dt);
id.setFileName(fileInfo.fileName());
id.setPath(fileInfo.path());
id.setUniqueHash(QString::fromUtf8(getUniqueHashVersion(2)), fileInfo.size());
id.setType(type);
return id;
}
HistoryImageId DImg::addAsReferredImage(const QString& filePath, HistoryImageId::Type type)
{
HistoryImageId id = createHistoryImageId(filePath, type);
m_priv->imageHistory.purgePathFromReferredImages(id.path(), id.fileName());
addAsReferredImage(id);
return id;
}
void DImg::addAsReferredImage(const HistoryImageId& id)
{
m_priv->imageHistory << id;
}
void DImg::insertAsReferredImage(int afterHistoryStep, const HistoryImageId& id)
{
m_priv->imageHistory.insertReferredImage(afterHistoryStep, id);
}
void DImg::addCurrentUniqueImageId(const QString& uuid)
{
m_priv->imageHistory.adjustCurrentUuid(uuid);
}
void DImg::addFilterAction(const Digikam::FilterAction& action)
{
m_priv->imageHistory << action;
}
const DImageHistory& DImg::getItemHistory() const
{
return m_priv->imageHistory;
}
DImageHistory& DImg::getItemHistory()
{
return m_priv->imageHistory;
}
void DImg::setItemHistory(const DImageHistory& history)
{
m_priv->imageHistory = history;
}
bool DImg::hasImageHistory() const
{
if (m_priv->imageHistory.isEmpty())
{
return false;
}
else
{
return true;
}
}
DImageHistory DImg::getOriginalImageHistory() const
{
return attribute(QLatin1String("originalImageHistory")).value<DImageHistory>();
}
void DImg::setHistoryBranch(bool isBranch)
{
setHistoryBranchAfter(getOriginalImageHistory(), isBranch);
}
void DImg::setHistoryBranchAfter(const DImageHistory& historyBeforeBranch, bool isBranch)
{
int addedSteps = m_priv->imageHistory.size() - historyBeforeBranch.size();
setHistoryBranchForLastSteps(addedSteps, isBranch);
}
void DImg::setHistoryBranchForLastSteps(int numberOfLastHistorySteps, bool isBranch)
{
int firstStep = m_priv->imageHistory.size() - numberOfLastHistorySteps;
if (firstStep < m_priv->imageHistory.size())
{
if (isBranch)
{
m_priv->imageHistory[firstStep].action.addFlag(FilterAction::ExplicitBranch);
}
else
{
m_priv->imageHistory[firstStep].action.removeFlag(FilterAction::ExplicitBranch);
}
}
}
QString DImg::colorModelToString(COLORMODEL colorModel)
{
switch (colorModel)
{
case RGB:
{
return i18nc("Color Model: RGB", "RGB");
}
case GRAYSCALE:
{
return i18nc("Color Model: Grayscale", "Grayscale");
}
case MONOCHROME:
{
return i18nc("Color Model: Monochrome", "Monochrome");
}
case INDEXED:
{
return i18nc("Color Model: Indexed", "Indexed");
}
case YCBCR:
{
return i18nc("Color Model: YCbCr", "YCbCr");
}
case CMYK:
{
return i18nc("Color Model: CMYK", "CMYK");
}
case CIELAB:
{
return i18nc("Color Model: CIE L*a*b*", "CIE L*a*b*");
}
case COLORMODELRAW:
{
return i18nc("Color Model: Uncalibrated (RAW)", "Uncalibrated (RAW)");
}
case COLORMODELUNKNOWN:
default:
{
return i18nc("Color Model: Unknown", "Unknown");
}
}
}
bool DImg::isAnimatedImage(const QString& filePath)
{
QImageReader reader(filePath);
reader.setDecideFormatFromContent(true);
if (reader.supportsAnimation() &&
(reader.imageCount() > 1))
{
qCDebug(DIGIKAM_DIMG_LOG) << "File \"" << filePath << "\" is an animated image";
return true;
}
return false;
}
int DImg::exifOrientation(const QString& filePath)
{
QVariant preview(attribute(QLatin1String("fromRawEmbeddedPreview")));
return LoadSaveThread::exifOrientation(filePath,
DMetadata(getMetadata()),
(detectedFormat() == DImg::RAW),
(preview.isValid() && preview.toBool()));
}
QByteArray DImg::createUniqueHash(const QString& filePath, const QByteArray& ba)
{
// Create the unique ID
QCryptographicHash md5(QCryptographicHash::Md5);
// First, read the Exif data into the hash
md5.addData(ba);
// Second, read in the first 8KB of the file
QFile qfile(filePath);
char databuf[8192];
QByteArray hash;
if (qfile.open(QIODevice::Unbuffered | QIODevice::ReadOnly))
{
int readlen = 0;
if ((readlen = qfile.read(databuf, 8192)) > 0)
{
QByteArray size;<--- Shadow variable
md5.addData(databuf, readlen);
md5.addData(size.setNum(qfile.size()));
hash = md5.result().toHex();
}
qfile.close();
}
return hash;
}
QByteArray DImg::createUniqueHashV2(const QString& filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::Unbuffered | QIODevice::ReadOnly))
{
return QByteArray();
}
QCryptographicHash md5(QCryptographicHash::Md5);
// Specified size: 100 kB; but limit to file size
const qint64 specifiedSize = 100 * 1024; // 100 kB
qint64 size = qMin(file.size(), specifiedSize);<--- Shadow variable
if (size)
{
QScopedArrayPointer<char> databuf(new char[size] { 0 });
int read;
// Read first 100 kB
if ((read = file.read(databuf.data(), size)) > 0)
{
md5.addData(databuf.data(), read);
}
// Read last 100 kB
file.seek(file.size() - size);
if ((read = file.read(databuf.data(), size)) > 0)
{
#if (QT_VERSION >= QT_VERSION_CHECK(6, 3, 0))
md5.addData(QByteArrayView(databuf.data(), read));
#else
md5.addData(databuf.data(), read);
#endif
}
}
file.close();
return md5.result().toHex();
}
QByteArray DImg::createUniqueHashV3(const QString& filePath)
{
QFile file(filePath);
if (!file.open(QIODevice::Unbuffered | QIODevice::ReadOnly))
{
return QByteArray();
}
QCryptographicHash md5(QCryptographicHash::Md5);
// maximum size: 100 kB for the first block, all other
// possible 5 blocks up to 25 kB; but limit to file size
const qint64 firstSize = 100 * 1024; // 100 kB
const qint64 nextSize = 25 * 1024; // 25 kB
const qint64 fsize = qMin(file.size(), firstSize);
const qint64 bsize = file.size() - fsize;
const qint64 block = qMin(bsize, nextSize);
const qint64 step = (bsize - block) / 5 + 1;
if (fsize)
{
QScopedArrayPointer<char> databuf(new char[fsize] { 0 });
qint64 read;
for (int sp = 0 ; sp < 6 ; ++sp)
{
qint64 rsize = !sp ? fsize : block;
qint64 rstep = !sp ? 0 : step * sp + fsize;
file.seek(qMin(rstep, file.size() - rsize));
if ((read = file.read(databuf.data(), rsize)) > 0)
{
#if (QT_VERSION >= QT_VERSION_CHECK(6, 3, 0))
md5.addData(QByteArrayView(databuf.data(), read));
#else
md5.addData(databuf.data(), read);
#endif
}
if (file.atEnd())
{
break;
}
}
}
file.close();
return md5.result().toHex();
}
} // namespace Digikam
|