Debian Codegraph @

src/util/dimagehandlerlibs.cpp

raw
1 // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "private/dimagehandlerlibs_p.h"
6
7 #ifndef DTK_DISABLE_EX_IMAGE_FORMAT
8
9 #include <QLibrary>
10 #include <QFileInfo>
11 #include <QDateTime>
12 #include <QImageReader>
13
14 DLibFreeImage::DLibFreeImage()
15 {
16 freeImage = new QLibrary("freeimage", "3");
17
18 if (!freeImage->load()) {
19 delete freeImage;
20 freeImage = nullptr;
21 return;
22 }
23
24 auto initFunctionError = [this]() {
25 freeImage->unload();
26 delete freeImage;
27 freeImage = nullptr;
28 };
29
30 #define INIT_FUNCTION_FREEIMAGE(Name) \
31 Name = reinterpret_cast<decltype(Name)>(freeImage->resolve(#Name)); \
32 if (!Name) { \
33 initFunctionError(); \
34 return; \
35 }
36
37 INIT_FUNCTION_FREEIMAGE(FreeImage_Load);
38 INIT_FUNCTION_FREEIMAGE(FreeImage_Unload);
39 INIT_FUNCTION_FREEIMAGE(FreeImage_Save);
40 INIT_FUNCTION_FREEIMAGE(FreeImage_FIFSupportsReading);
41 INIT_FUNCTION_FREEIMAGE(FreeImage_GetFileType);
42 INIT_FUNCTION_FREEIMAGE(FreeImage_GetFIFFromFilename);
43 INIT_FUNCTION_FREEIMAGE(FreeImage_GetImageType);
44
45 INIT_FUNCTION_FREEIMAGE(FreeImage_GetBPP);
46 INIT_FUNCTION_FREEIMAGE(FreeImage_GetWidth);
47 INIT_FUNCTION_FREEIMAGE(FreeImage_GetHeight);
48 INIT_FUNCTION_FREEIMAGE(FreeImage_GetRedMask);
49 INIT_FUNCTION_FREEIMAGE(FreeImage_GetGreenMask);
50 INIT_FUNCTION_FREEIMAGE(FreeImage_GetBlueMask);
51
52 INIT_FUNCTION_FREEIMAGE(FreeImage_GetThumbnail);
53 INIT_FUNCTION_FREEIMAGE(FreeImage_SetThumbnail);
54 INIT_FUNCTION_FREEIMAGE(FreeImage_ConvertToRawBits);
55
56 INIT_FUNCTION_FREEIMAGE(FreeImage_GetMetadataCount);
57 INIT_FUNCTION_FREEIMAGE(FreeImage_FindFirstMetadata);
58 INIT_FUNCTION_FREEIMAGE(FreeImage_FindNextMetadata);
59 INIT_FUNCTION_FREEIMAGE(FreeImage_FindCloseMetadata);
60
61 INIT_FUNCTION_FREEIMAGE(FreeImage_GetTagKey);
62 INIT_FUNCTION_FREEIMAGE(FreeImage_GetTagValue);
63 INIT_FUNCTION_FREEIMAGE(FreeImage_TagToString);
64 INIT_FUNCTION_FREEIMAGE(FreeImage_Rotate);
65 }
66
67 DLibFreeImage::~DLibFreeImage()
68 {
69 if (freeImage) {
70 delete freeImage;
71 }
72 }
73
74 bool DLibFreeImage::isValid()
75 {
76 return freeImage;
77 }
78
79 bool DLibFreeImage::findMetaData(FREE_IMAGE_MDMODEL model, FIBITMAP *dib, QHash<QString, QString> &data)
80 {
81 bool ret = false;
82 if (freeImage) {
83 if (FreeImage_GetMetadataCount(model, dib)) {
84 FITAG *tag = nullptr;
85 FIMETADATA *mdhandle = nullptr;
86 mdhandle = FreeImage_FindFirstMetadata(model, dib, &tag);
87 if (mdhandle) {
88 do {
89 QString value;
90
91 // Warning: FreeImage_TagToString is not thread-safe, add mutex protection.
92 apiMutex.lock();
93 value = QString(FreeImage_TagToString(model, tag, nullptr));
94 apiMutex.unlock();
95
96 data.insert(FreeImage_GetTagKey(tag), value);
97 ret = true;
98 } while (FreeImage_FindNextMetadata(mdhandle, &tag));
99 FreeImage_FindCloseMetadata(mdhandle);
100 }
101 }
102 }
103
104 return ret;
105 }
106
107 QHash<QString, QString> DLibFreeImage::findAllMetaData(const QString &fileName)
108 {
109 FIBITMAP *dib = readFileToFIBITMAP(fileName, FIF_LOAD_NOPIXELS);
110 QHash<QString, QString> admMap;
111 for (int i = FIMD_EXIF_MAIN; i <= FIMD_IPTC; ++i) {
112 findMetaData(FREE_IMAGE_MDMODEL(i), dib, admMap);
113 }
114
115 QFileInfo info(fileName);
116 if (admMap.contains("DateTime")) {
117 // Get first DateTime.
118 QDateTime time = QDateTime::fromString(admMap.value("DateTime"), "yyyy:MM:dd hh:mm:ss");
119 admMap.insert("DateTimeOriginal", time.toString("yyyy/MM/dd hh:mm"));
120 } else {
121 admMap.insert("DateTimeOriginal", info.lastModified().toString("yyyy/MM/dd HH:mm"));
122 }
123 admMap.insert("DateTimeDigitized", info.lastModified().toString("yyyy/MM/dd HH:mm"));
124
125 // The value of width and height might incorrect
126 QImageReader reader(fileName);
127 int w = reader.size().width();
128 w = w > 0 ? w : static_cast<int>(FreeImage_GetWidth(dib));
129 int h = reader.size().height();
130 h = h > 0 ? h : static_cast<int>(FreeImage_GetHeight(dib));
131 admMap.insert("Dimension", QString::number(w) + "x" + QString::number(h));
132 admMap.insert("FileName", info.fileName());
133 admMap.insert("FileFormat", info.suffix());
134
135 static auto formatDataSize = [](qint64 size) -> QString {
136 static const QStringList suffix = {"B", "KB", "MB", "GB", "TB", "PB"};
137 int level = 0;
138 double bytes = size;
139 while (bytes >= 1024 && level < (suffix.length() - 1)) {
140 bytes /= 1024;
141 ++level;
142 }
143 return QString("%1%2").arg(bytes, 0, 'f', 1).arg(suffix[level]);
144 };
145 admMap.insert("FileSize", formatDataSize(info.size()));
146
147 FreeImage_Unload(dib);
148 return admMap;
149 }
150
151 FIBITMAP *DLibFreeImage::readFileToFIBITMAP(const QString &fileName, int flags, FREE_IMAGE_FORMAT fif)
152 {
153 QByteArray b = fileName.toUtf8();
154 const char *pc = b.data();
155
156 // Detect file format.
157 if (FIF_UNKNOWN == fif) {
158 fif = FreeImage_GetFileType(pc, 0);
159 if (FIF_UNKNOWN == fif) {
160 fif = FreeImage_GetFIFFromFilename(pc);
161 }
162 }
163
164 if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) {
165 FIBITMAP *dib = FreeImage_Load(fif, pc, flags);
166 return dib;
167 }
168 return nullptr;
169 }
170
171 bool DLibFreeImage::writeFIBITMAPToFile(FIBITMAP *dib, const QString &fileName, int flags)
172 {
173 FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
174 bool bSuccess = false;
175 const QByteArray ba = fileName.toUtf8();
176 const char *pc = ba.data();
177 // Try to guess the file format from the file extension
178 fif = FreeImage_GetFIFFromFilename(pc);
179 FREE_IMAGE_FORMAT realfif = FIF_UNKNOWN;
180
181 if (fif == FIF_UNKNOWN) {
182 realfif = FreeImage_GetFileType(pc, 0);
183 }
184
185 if (fif != FIF_UNKNOWN) {
186 bSuccess = FreeImage_Save(fif, dib, pc, flags);
187 } else if (realfif != FIF_UNKNOWN) {
188 bSuccess = FreeImage_Save(realfif, dib, pc, flags);
189 }
190
191 return bSuccess;
192 }
193
194 QImage DLibFreeImage::FIBITMAPToQImage(FIBITMAP *dib) const
195 {
196 if (!dib || FreeImage_GetImageType(dib) == FIT_UNKNOWN)
197 return QImage(0, 0, QImage::Format_Invalid);
198 int width = static_cast<int>(FreeImage_GetWidth(dib));
199 int height = static_cast<int>(FreeImage_GetHeight(dib));
200 int depth = static_cast<int>(FreeImage_GetBPP(dib));
201
202 switch (depth) {
203 case 1: {
204 QImage result(width, height, QImage::Format_Mono);
205 FreeImage_ConvertToRawBits(result.scanLine(0), dib, result.bytesPerLine(), 1, 0, 0, 0, true);
206 return result;
207 }
208 case 4: {
209 // NOTE: QImage do not support 4-bit, convert it to 8-bit
210 QImage result(width, height, QImage::Format_Indexed8);
211 FreeImage_ConvertToRawBits(result.scanLine(0), dib, result.bytesPerLine(), 8, 0, 0, 0, true);
212 return result;
213 }
214 case 8: {
215 QImage result(width, height, QImage::Format_Indexed8);
216 FreeImage_ConvertToRawBits(result.scanLine(0), dib, result.bytesPerLine(), 8, 0, 0, 0, true);
217 return result;
218 }
219 case 16:
220 if ((FreeImage_GetRedMask(dib) == FI16_555_RED_MASK) && (FreeImage_GetGreenMask(dib) == FI16_555_GREEN_MASK) &&
221 (FreeImage_GetBlueMask(dib) == FI16_555_BLUE_MASK)) {
222 // 5-5-5
223 QImage result(width, height, QImage::Format_RGB555);
224 FreeImage_ConvertToRawBits(result.scanLine(0),
225 dib,
226 result.bytesPerLine(),
227 16,
228 FI16_555_RED_MASK,
229 FI16_555_GREEN_MASK,
230 FI16_555_BLUE_MASK,
231 true);
232 return result;
233 } else {
234 // 5-6-5
235 QImage result(width, height, QImage::Format_RGB16);
236 FreeImage_ConvertToRawBits(result.scanLine(0),
237 dib,
238 result.bytesPerLine(),
239 16,
240 FI16_565_RED_MASK,
241 FI16_565_GREEN_MASK,
242 FI16_565_BLUE_MASK,
243 true);
244 return result;
245 }
246 case 24: {
247 QImage result(width, height, QImage::Format_RGB32);
248 FreeImage_ConvertToRawBits(result.scanLine(0),
249 dib,
250 result.bytesPerLine(),
251 32,
252 FI_RGBA_RED_MASK,
253 FI_RGBA_GREEN_MASK,
254 FI_RGBA_BLUE_MASK,
255 true);
256 return result;
257 }
258 case 32: {
259 QImage result(width, height, QImage::Format_ARGB32);
260 FreeImage_ConvertToRawBits(result.scanLine(0),
261 dib,
262 result.bytesPerLine(),
263 32,
264 FI_RGBA_RED_MASK,
265 FI_RGBA_GREEN_MASK,
266 FI_RGBA_BLUE_MASK,
267 true);
268 return result;
269 }
270 case 48:
271 case 64:
272 case 96:
273 case 128:
274 default:
275 break;
276 }
277
278 return QImage(0, 0, QImage::Format_Invalid);
279 }
280
281 ExifImageOrientation DLibFreeImage::imageOrientation(const QString &fileName)
282 {
283 ExifImageOrientation oreintation = Undefined;
284
285 FIBITMAP *dib = readFileToFIBITMAP(fileName, FIF_LOAD_NOPIXELS);
286 // Metadata may be null sometimes, check if metadata exist.
287 if (0 == FreeImage_GetMetadataCount(FIMD_EXIF_MAIN, dib)) {
288 FreeImage_Unload(dib);
289 return oreintation;
290 }
291
292 FITAG *tag = nullptr;
293 FIMETADATA *mdhandle = nullptr;
294 mdhandle = FreeImage_FindFirstMetadata(FIMD_EXIF_MAIN, dib, &tag);
295 if (mdhandle) {
296 do {
297 if (qstrcmp(FreeImage_GetTagKey(tag), "Orientation") == 0) {
298 oreintation = ExifImageOrientation(*static_cast<const WORD *>(FreeImage_GetTagValue(tag)));
299 break;
300 }
301 } while (FreeImage_FindNextMetadata(mdhandle, &tag));
302 FreeImage_FindCloseMetadata(mdhandle);
303 }
304
305 FreeImage_Unload(dib);
306 return oreintation;
307 }
308
309 bool DLibFreeImage::rotateImageFile(const QString &fileName, int angle, QString &errorString)
310 {
311 FIBITMAP *dib = readFileToFIBITMAP(fileName);
312 if (nullptr == dib) {
313 errorString = "Unsupported format";
314 return false;
315 }
316
317 FIBITMAP *rotateRes = FreeImage_Rotate(dib, -angle, nullptr);
318 if (rotateRes) {
319 // Regenerate thumbnail if it's exits
320 // Image formats that currently support thumbnail saving are
321 // JPEG (JFIF formats), EXR, TGA and TIFF.
322 if (FreeImage_GetThumbnail(dib)) {
323 FIBITMAP *thumb = FreeImage_GetThumbnail(dib);
324 FIBITMAP *rotateThumb = FreeImage_Rotate(thumb, -angle, nullptr);
325
326 FreeImage_SetThumbnail(rotateRes, rotateThumb);
327 FreeImage_Unload(rotateThumb);
328 }
329 }
330
331 FREE_IMAGE_FORMAT f = FreeImage_GetFIFFromFilename(fileName.toUtf8().data());
332 if (f == FIF_UNKNOWN) {
333 FreeImage_Unload(dib);
334 FreeImage_Unload(rotateRes);
335 errorString = "Rotate image format error";
336 return false;
337 }
338
339 if (!writeFIBITMAPToFile(rotateRes, fileName)) {
340 FreeImage_Unload(dib);
341 FreeImage_Unload(rotateRes);
342 errorString = "Rotate image save failed, unknown format";
343 return false;
344 }
345
346 FreeImage_Unload(dib);
347 FreeImage_Unload(rotateRes);
348 return true;
349 }
350
351 DLibRaw::DLibRaw()
352 {
353 libraw = new QLibrary("libraw");
354 if (!libraw->load()) {
355 delete libraw;
356 libraw = nullptr;
357 return;
358 }
359
360 auto initFunctionError = [this]() {
361 libraw->unload();
362 delete libraw;
363 libraw = nullptr;
364 };
365
366 #define INIT_FUNCTION_LIBRAW(Name) \
367 Name = reinterpret_cast<decltype(Name)>(libraw->resolve(#Name)); \
368 if (!Name) { \
369 initFunctionError(); \
370 return; \
371 }
372
373 INIT_FUNCTION_LIBRAW(libraw_strerror);
374 INIT_FUNCTION_LIBRAW(libraw_init);
375 INIT_FUNCTION_LIBRAW(libraw_open_file);
376 INIT_FUNCTION_LIBRAW(libraw_open_buffer);
377 INIT_FUNCTION_LIBRAW(libraw_unpack);
378 INIT_FUNCTION_LIBRAW(libraw_unpack_thumb);
379 INIT_FUNCTION_LIBRAW(libraw_close);
380 INIT_FUNCTION_LIBRAW(libraw_dcraw_process);
381 INIT_FUNCTION_LIBRAW(libraw_dcraw_make_mem_image);
382 INIT_FUNCTION_LIBRAW(libraw_dcraw_make_mem_thumb);
383 INIT_FUNCTION_LIBRAW(libraw_dcraw_clear_mem);
384 }
385
386 DLibRaw::~DLibRaw()
387 {
388 if (libraw) {
389 delete libraw;
390 }
391 }
392
393 bool DLibRaw::isValid()
394 {
395 return libraw;
396 }
397
398 QImage DLibRaw::loadImage(const QString &fileName, QString &errString, QSize requestSize)
399 {
400 QImage image;
401 libraw_data_t *rawData = libraw_init(0);
402 if (!rawData) {
403 errString = QStringLiteral("Create new libraw object failed!");
404 return image;
405 }
406
407 int ret = libraw_open_file(rawData, fileName.toUtf8().data());
408 if (LIBRAW_SUCCESS == ret) {
409 ret = readImage(rawData, image, requestSize);
410 }
411 libraw_close(rawData);
412
413 if (LIBRAW_SUCCESS != ret) {
414 errString = errorString(ret);
415 }
416 return image;
417 }
418
419 QImage DLibRaw::loadImage(QByteArray &data, QString &errString, QSize requestSize)
420 {
421 QImage image;
422 libraw_data_t *rawData = libraw_init(0);
423 if (!rawData) {
424 errString = QStringLiteral("Create new libraw object failed!");
425 return image;
426 }
427
428 int ret = libraw_open_buffer(rawData, reinterpret_cast<void *>(data.data()), static_cast<size_t>(data.size()));
429 if (LIBRAW_SUCCESS == ret) {
430 ret = readImage(rawData, image, requestSize);
431 }
432 libraw_close(rawData);
433
434 if (LIBRAW_SUCCESS != ret) {
435 errString = errorString(ret);
436 }
437 return image;
438 }
439
440 int DLibRaw::readImage(libraw_data_t *rawData, QImage &image, QSize requestSize)
441 {
442 if (!rawData) {
443 return LIBRAW_INPUT_CLOSED;
444 }
445
446 int ret = LIBRAW_UNSPECIFIED_ERROR;
447 int errCode = LIBRAW_SUCCESS;
448 libraw_processed_image_t *output = nullptr;
449 // Try to read thumbnail image if possible.
450 if (!requestSize.isEmpty() &&
451 (requestSize.width() < rawData->thumbnail.twidth || requestSize.height() < rawData->thumbnail.theight)) {
452 ret = libraw_unpack_thumb(rawData);
453 if (LIBRAW_SUCCESS == ret) {
454 output = libraw_dcraw_make_mem_thumb(rawData, &errCode);
455 if (LIBRAW_SUCCESS != errCode && output) {
456 libraw_dcraw_clear_mem(output);
457 }
458 }
459 }
460
461 // Read default image if no thumbnail.
462 if (!output) {
463 ret = libraw_unpack(rawData);
464 if (LIBRAW_SUCCESS != ret) {
465 return ret;
466 }
467 ret = libraw_dcraw_process(rawData);
468 if (LIBRAW_SUCCESS != ret) {
469 return ret;
470 }
471
472 output = libraw_dcraw_make_mem_image(rawData, &errCode);
473 if (LIBRAW_SUCCESS != errCode) {
474 if (output) {
475 libraw_dcraw_clear_mem(output);
476 }
477
478 // Can't read data, return.
479 return errCode;
480 }
481 }
482
483 if (LIBRAW_IMAGE_JPEG == output->type) {
484 image.loadFromData(output->data, static_cast<int>(output->data_size), "JPEG");
485 if (rawData->sizes.flip) {
486 QTransform rotation;
487 int angle = 0;
488
489 // Image orientation (0 if does not require rotation; 3 if requires 180-deg rotation;
490 // 5 if 90 deg counterclockwise, 6 if 90 deg clockwise).
491 switch (rawData->sizes.flip) {
492 case 3:
493 angle = 180;
494 break;
495 case 5:
496 angle = -90;
497 break;
498 case 6:
499 angle = 90;
500 break;
501 default:
502 break;
503 }
504
505 if (angle != 0) {
506 rotation.rotate(angle);
507 image = image.transformed(rotation);
508 }
509 }
510
511 } else {
512 int numPixels = output->width * output->height;
513 int colorSize = output->bits / 8;
514 int pixelSize = output->colors * colorSize;
515 uchar *pixels = new uchar[numPixels * 4];
516 uchar *data = output->data;
517
518 for (int i = 0; i < numPixels; i++, data += pixelSize) {
519 if (output->colors == 3) {
520 pixels[i * 4] = data[2 * colorSize];
521 pixels[i * 4 + 1] = data[1 * colorSize];
522 pixels[i * 4 + 2] = data[0];
523 } else {
524 pixels[i * 4] = data[0];
525 pixels[i * 4 + 1] = data[0];
526 pixels[i * 4 + 2] = data[0];
527 }
528 }
529
530 // QImage::Format_RGB32 will cause window transparent
531 image = QImage(pixels, output->width, output->height, QImage::Format_RGB32).convertToFormat(QImage::Format_ARGB32);
532 delete[] pixels;
533 }
534
535 libraw_dcraw_clear_mem(output);
536 return LIBRAW_SUCCESS;
537 }
538
539 QString DLibRaw::errorString(int errorCode)
540 {
541 return QString(libraw_strerror(errorCode));
542 }
543
544 #endif