-
-
Notifications
You must be signed in to change notification settings - Fork 699
Expand file tree
/
Copy pathPhotoCodec.cs
More file actions
1568 lines (1258 loc) Β· 50 KB
/
PhotoCodec.cs
File metadata and controls
1568 lines (1258 loc) Β· 50 KB
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
ο»Ώ/*
ImageGlass Project - Image viewer for Windows
Copyright (C) 2010 - 2026 DUONG DIEU PHAP
Project homepage: https://imageglass.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using DirectN;
using ImageGlass.WebP;
using ImageMagick;
using ImageMagick.Formats;
using PhotoSauce.MagicScaler;
using System.Runtime.CompilerServices;
using System.Text;
using WicNet;
namespace ImageGlass.Base.Photoing.Codecs;
/// <summary>
/// Handles reading and writing image file formats.
/// </summary>
public static class PhotoCodec
{
#region Public functions
/// <summary>
/// Loads metadata from file.
/// </summary>
/// <param name="filePath">Full path of the file</param>
public static IgMetadata? LoadMetadata(string? filePath, CodecReadOptions? options = null)
{
FileInfo? fi = null;
var meta = new IgMetadata() { FilePath = filePath ?? string.Empty };
try
{
fi = new FileInfo(filePath);
}
catch { }
if (fi == null) return meta;
var ext = fi.Extension.ToUpperInvariant();
meta.FileName = fi.Name;
meta.FileExtension = ext;
meta.FolderPath = fi.DirectoryName ?? string.Empty;
meta.FolderName = Path.GetFileName(meta.FolderPath);
meta.FileSize = fi.Length;
meta.FileCreationTime = fi.CreationTime;
meta.FileLastWriteTime = fi.LastWriteTime;
meta.FileLastAccessTime = fi.LastAccessTime;
try
{
var settings = ParseSettings(options, false, filePath);
using var imgC = new MagickImageCollection();
if (filePath.Length > 260)
{
var allBytes = File.ReadAllBytes(filePath);
imgC.Ping(allBytes, settings);
}
else
{
imgC.Ping(filePath, settings);
}
meta.FrameIndex = 0;
meta.FrameCount = imgC.Count;
if (imgC.Count > 0)
{
var frameIndex = options?.FrameIndex ?? 0;
// Check if frame index is greater than upper limit
if (frameIndex >= imgC.Count)
frameIndex = 0;
// Check if frame index is less than lower limit
else if (frameIndex < 0)
frameIndex = imgC.Count - 1;
meta.FrameIndex = (uint)frameIndex;
using var imgM = imgC[frameIndex];
// image size
meta.OriginalWidth = imgM.BaseWidth;
meta.OriginalHeight = imgM.BaseHeight;
if (options?.AutoScaleDownLargeImage == true)
{
var newSize = GetMaxImageRenderSize(imgM.BaseWidth, imgM.BaseHeight);
meta.RenderedWidth = (uint)newSize.Width;
meta.RenderedHeight = (uint)newSize.Height;
}
else
{
meta.RenderedWidth = imgM.Width;
meta.RenderedHeight = imgM.Height;
}
// DPI
var density = imgM.Density;
// Convert units to inch
meta.DpiX = (float)density.X * 2.54f;
meta.DpiY = (float)density.Y * 2.54f;
// image color
meta.HasAlpha = imgC.Any(i => i.HasAlpha);
meta.ColorSpace = imgM.ColorSpace.ToString();
meta.CanAnimate = CheckAnimatedFormat(imgC, ext);
// EXIF profile
if (imgM.GetExifProfile() is IExifProfile exifProfile)
{
// ExifRatingPercent
meta.ExifRatingPercent = GetExifValue(exifProfile, ExifTag.RatingPercent);
// ExifDateTimeOriginal
var dt = GetExifValue(exifProfile, ExifTag.DateTimeOriginal);
meta.ExifDateTimeOriginal = BHelper.ConvertDateTime(dt);
// ExifDateTime
dt = GetExifValue(exifProfile, ExifTag.DateTime);
meta.ExifDateTime = BHelper.ConvertDateTime(dt);
meta.ExifArtist = GetExifValue(exifProfile, ExifTag.Artist);
meta.ExifCopyright = GetExifValue(exifProfile, ExifTag.Copyright);
meta.ExifSoftware = GetExifValue(exifProfile, ExifTag.Software);
meta.ExifImageDescription = GetExifValue(exifProfile, ExifTag.ImageDescription);
meta.ExifModel = GetExifValue(exifProfile, ExifTag.Model);
meta.ExifISOSpeed = (int?)GetExifValue(exifProfile, ExifTag.ISOSpeed);
var rational = GetExifValue(exifProfile, ExifTag.ExposureTime);
meta.ExifExposureTime = rational.Denominator == 0
? null
: rational.Numerator / rational.Denominator;
rational = GetExifValue(exifProfile, ExifTag.FNumber);
meta.ExifFNumber = rational.Denominator == 0
? null
: rational.Numerator / rational.Denominator;
rational = GetExifValue(exifProfile, ExifTag.FocalLength);
meta.ExifFocalLength = rational.Denominator == 0
? null
: rational.Numerator / rational.Denominator;
}
else
{
try
{
using var fs = File.OpenRead(filePath);
using var img = Image.FromStream(fs, false, false);
var enc = new ASCIIEncoding();
var EXIF_DateTimeOriginal = 0x9003; //36867
var EXIF_DateTime = 0x0132;
try
{
// get EXIF_DateTimeOriginal
var pi = img.GetPropertyItem(EXIF_DateTimeOriginal);
var dateTimeText = enc.GetString(pi.Value, 0, pi.Len - 1);
if (DateTime.TryParseExact(dateTimeText, "yyyy:MM:dd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out var exifDateTimeOriginal))
{
meta.ExifDateTimeOriginal = exifDateTimeOriginal;
}
}
catch { }
try
{
// get EXIF_DateTime
var pi = img.GetPropertyItem(EXIF_DateTime);
var dateTimeText = enc.GetString(pi.Value, 0, pi.Len - 1);
if (DateTime.TryParseExact(dateTimeText, "yyyy:MM:dd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out var exifDateTime))
{
meta.ExifDateTime = exifDateTime;
}
}
catch { }
}
catch { }
}
// Color profile
if (imgM.GetColorProfile() is IColorProfile colorProfile)
{
meta.ColorProfile = colorProfile.ColorSpace.ToString();
if (!string.IsNullOrWhiteSpace(colorProfile.Description))
{
meta.ColorProfile = $"{colorProfile.Description} ({meta.ColorProfile})";
}
}
}
}
catch { }
return meta;
}
/// <summary>
/// Loads image file async.
/// </summary>
/// <param name="filePath">Full path of the file</param>
/// <param name="options">Loading options</param>
/// <param name="token">Cancellation token</param>
public static async Task<IgImgData> LoadAsync(string filePath,
CodecReadOptions? options = null, ImgTransform? transform = null,
CancellationToken? token = null)
{
options ??= new();
var cancelToken = token ?? default;
try
{
var (loadSuccessful, result, ext, settings) = ReadWithStream(filePath, options, transform);
if (!loadSuccessful)
{
result = await LoadWithMagickImageAsync(filePath, ext, settings, options, transform, cancelToken);
}
return result;
}
catch (OperationCanceledException) { }
return new IgImgData();
}
/// <summary>
/// Gets thumbnail from image.
/// </summary>
public static async Task<Bitmap?> GetThumbnailAsync(string filePath, uint width, uint height)
{
if (string.IsNullOrEmpty(filePath) || width == 0 || height == 0) return null;
var options = new CodecReadOptions()
{
Width = width,
Height = height,
MinDimensionToUseWIC = 0,
FirstFrameOnly = true,
UseEmbeddedThumbnailRawFormats = true,
UseEmbeddedThumbnailOtherFormats = true,
ApplyColorProfileForAll = false,
};
var settings = ParseSettings(options, false, filePath);
var ext = Path.GetExtension(filePath).ToLowerInvariant();
var imgData = await ReadMagickImageAsync(filePath, ext, settings, options, null, new());
if (imgData?.SingleFrameImage != null)
{
return imgData.SingleFrameImage.ToBitmap();
}
return null;
}
/// <summary>
/// Gets thumbnail from image.
/// </summary>
public static Bitmap? GetThumbnail(string filePath, uint width, uint height)
{
return BHelper.RunSync(() => GetThumbnailAsync(filePath, width, height));
}
/// <summary>
/// Gets embedded thumbnail.
/// </summary>
public static WicBitmapSource? GetEmbeddedThumbnail(string filePath, bool rawThumbnail = true, bool exifThumbnail = true, CancellationToken token = default)
{
if (string.IsNullOrEmpty(filePath)) return null;
try
{
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException) { return null; }
var settings = ParseSettings(new() { FirstFrameOnly = true }, false, filePath);
WicBitmapSource? result = null;
using var imgM = new MagickImage();
imgM.Ping(filePath, settings);
// get RAW embedded thumbnail
if (rawThumbnail)
{
try
{
token.ThrowIfCancellationRequested();
// try to get thumbnail
if (imgM.GetProfile("dng:thumbnail") is IImageProfile profile
&& profile.ToReadOnlySpan() is ReadOnlySpan<byte> thumbnailData)
{
imgM.Read(thumbnailData, settings);
imgM.AutoOrient();
result = BHelper.ToWicBitmapSource(imgM.ToBitmapSource(), imgM.HasAlpha);
}
}
catch (OperationCanceledException) { return null; }
catch { }
}
// Use JPEG embedded thumbnail
if (exifThumbnail && result == null)
{
try
{
token.ThrowIfCancellationRequested();
var exifProfile = imgM.GetExifProfile();
// Fetch the embedded thumbnail
using var thumbM = exifProfile?.CreateThumbnail();
if (thumbM != null)
{
thumbM.AutoOrient();
result = BHelper.ToWicBitmapSource(thumbM.ToBitmapSource(), thumbM.HasAlpha);
}
}
catch (OperationCanceledException) { return null; }
catch { }
}
return result;
}
/// <summary>
/// Gets base64 thumbnail from image
/// </summary>
public static string GetThumbnailBase64(string filePath, uint width, uint height)
{
var thumbnail = GetThumbnail(filePath, width, height);
if (thumbnail != null)
{
using var imgM = new MagickImage();
imgM.Read(thumbnail);
return "data:image/png;charset=utf-8;base64," + imgM.ToBase64(MagickFormat.Png);
}
return string.Empty;
}
/// <summary>
/// Reads and processes the SVG file, replaces <c>#000</c> or <c>#fff</c>
/// by the corresponding hex color value of the <paramref name="darkMode"/>.
/// </summary>
public static async Task<MagickImage?> ReadSvgWithMagickAsync(string svgFilePath, bool? darkMode, uint? width, uint? height, CancellationToken token = default)
{
// set up Magick settings
var settings = ParseSettings(new CodecReadOptions()
{
Width = width ?? 0,
Height = height ?? 0,
}, false, svgFilePath);
var imgM = new MagickImage();
// change SVG icon color if requested
if (darkMode != null)
{
// preprocess SVG content
using var fs = new StreamReader(svgFilePath);
var svg = await fs.ReadToEndAsync(token);
if (darkMode.Value)
{
svg = svg.Replace("#000", "#fff");
}
else
{
svg = svg.Replace("#fff", "#000");
}
using var ms = new MemoryStream(Encoding.UTF8.GetBytes(svg));
imgM.Read(ms, settings);
}
else
{
await imgM.ReadAsync(svgFilePath, settings, token);
}
return imgM;
}
/// <summary>
/// Checks if the format can be written.
/// </summary>
public static bool CheckSupportFormatForSaving(string destFilePath)
{
return MagickFormatInfo.Create(destFilePath).SupportsWriting;
}
/// <summary>
/// Save as image file, use Magick.NET.
/// </summary>
/// <param name="srcFileName">Source filename to save</param>
/// <param name="destFilePath">Destination filename</param>
/// <param name="readOptions">Options for reading image file</param>
/// <param name="transform">Changes for writing image file</param>
/// <param name="quality">Quality</param>
/// <exception cref="FileFormatException"></exception>
public static async Task SaveAsync(string srcFileName, string destFilePath, CodecReadOptions readOptions, ImgTransform? transform = null, uint quality = 100, CancellationToken token = default)
{
var ext = Path.GetExtension(destFilePath).ToUpperInvariant();
try
{
if (!CheckSupportFormatForSaving(destFilePath))
{
throw new FileFormatException("IGE_001: Unsupported image format.");
}
var settings = ParseSettings(readOptions, true, srcFileName);
using var imgData = await ReadMagickImageAsync(
srcFileName,
Path.GetExtension(srcFileName),
settings,
readOptions with
{
// Magick.NET auto-corrects the rotation when saving,
// so we don't need to correct it manually.
CorrectRotation = false,
}, transform, token);
if (imgData.MultiFrameImage != null)
{
await imgData.MultiFrameImage.WriteAsync(destFilePath, token);
}
else if (imgData.SingleFrameImage != null)
{
imgData.SingleFrameImage.Quality = quality;
// resize ICO file if it's larger than 256
if (ext == ".ICO")
{
var imgW = imgData.SingleFrameImage.Width;
var imgH = imgData.SingleFrameImage.Height;
const int MAX_ICON_SIZE = 256;
if (imgW > MAX_ICON_SIZE || imgH > MAX_ICON_SIZE)
{
var iconSize = GetMaxImageRenderSize(imgW, imgH, MAX_ICON_SIZE);
imgData.SingleFrameImage.Scale((uint)iconSize.Width, (uint)iconSize.Height);
}
}
await imgData.SingleFrameImage.WriteAsync(destFilePath, token);
}
}
catch (OperationCanceledException) { }
}
/// <summary>
/// Save image file, use WIC if it supports, otherwise use Magick.NET.
/// </summary>
/// <param name="srcBitmap">Source bitmap to save</param>
/// <param name="destFilePath">Destination file path</param>
/// <param name="transform">Image transformation</param>
/// <param name="quality">JPEG/MIFF/PNG compression level</param>
/// <param name="format">New image format</param>
public static async Task SaveAsync(WicBitmapSource? srcBitmap, string destFilePath, ImgTransform? transform = null, uint quality = 100, MagickFormat format = MagickFormat.Unknown, CancellationToken token = default)
{
if (srcBitmap == null) return;
try
{
token.ThrowIfCancellationRequested();
// transform image
srcBitmap = TransformImage(srcBitmap, transform);
// get WIC encoder for the dest format
var encoder = WicEncoder.FromFileExtension(Path.GetExtension(destFilePath));
// if WIC supports this format
if (encoder != null)
{
srcBitmap.Save(destFilePath, encoder.ContainerFormat);
}
// use Magick.NET to save
else
{
// convert to Bitmap
using var bitmap = BHelper.ToGdiPlusBitmap(srcBitmap);
if (bitmap == null) return;
// convert to MagickImage
using var imgM = new MagickImage();
await Task.Run(() =>
{
imgM.Read(bitmap);
imgM.Quality = quality;
}, token);
// write image data to file
token.ThrowIfCancellationRequested();
if (format != MagickFormat.Unknown)
{
await imgM.WriteAsync(destFilePath, format, token);
}
else
{
await imgM.WriteAsync(destFilePath, token);
}
}
}
catch (OperationCanceledException) { }
}
/// <summary>
/// Exports image frames to files, using Magick.NET
/// </summary>
/// <param name="srcFilePath">The full path of source file</param>
/// <param name="destFolder">The destination folder to save to</param>
public static async IAsyncEnumerable<(int FrameNumber, string FileName)> SaveFramesAsync(string srcFilePath, string destFolder, [EnumeratorCancellation] CancellationToken token = default)
{
// create dirs unless it does not exist
Directory.CreateDirectory(destFolder);
using var imgColl = new MagickImageCollection(srcFilePath);
var index = 0;
foreach (var imgM in imgColl)
{
index++;
imgM.Quality = 100;
var newFilename = string.Empty;
try
{
newFilename = Path.GetFileNameWithoutExtension(srcFilePath)
+ " - " + index.ToString($"D{imgColl.Count.ToString().Length}")
+ ".png";
var destFilePath = Path.Combine(destFolder, newFilename);
await imgM.WriteAsync(destFilePath, MagickFormat.Png, token);
}
catch (OperationCanceledException) { break; }
catch { }
yield return (index, newFilename);
}
}
/// <summary>
/// Saves source bitmap image as base64 using Stream.
/// </summary>
/// <param name="srcBitmap">Source bitmap</param>
/// <param name="srcExt">Source file extension, example: .png</param>
/// <param name="destFilePath">Destination file</param>
public static async Task SaveAsBase64Async(WicBitmapSource? srcBitmap, string srcExt, string destFilePath, ImgTransform? transform = null, CancellationToken token = default)
{
if (srcBitmap == null) return;
var mimeType = BHelper.GetMIMEType(srcExt);
var header = $"data:{mimeType};base64,";
var srcFormat = BHelper.GetWicContainerFormatFromExtension(srcExt);
try
{
token.ThrowIfCancellationRequested();
srcBitmap = TransformImage(srcBitmap, transform);
token.ThrowIfCancellationRequested();
// convert bitmap to base64
using var ms = new MemoryStream();
srcBitmap.Save(ms, srcFormat);
var base64 = Convert.ToBase64String(ms.ToArray());
token.ThrowIfCancellationRequested();
// write base64 file
using var sw = new StreamWriter(destFilePath);
await sw.WriteAsync(header + base64).ConfigureAwait(false);
await sw.FlushAsync(token).ConfigureAwait(false);
sw.Close();
}
catch (OperationCanceledException) { }
}
/// <summary>
/// Saves image file as base64. Uses Magick.NET if <paramref name="transform"/>
/// has changes. Uses Stream if the format is supported, else uses Magick.NET.
/// </summary>
/// <param name="srcFilePath">Source file path</param>
/// <param name="destFilePath">Destination file path</param>
public static async Task SaveAsBase64Async(string srcFilePath, string destFilePath, CodecReadOptions readOptions, ImgTransform? transform = null, CancellationToken token = default)
{
if (transform.HasChanges)
{
using var imgC = new MagickImageCollection();
imgC.Ping(srcFilePath);
if (imgC.Count == 1)
{
using var imgM = imgC[0];
TransformImage(imgM, transform);
using var wicSrc = BHelper.ToWicBitmapSource(imgM.ToBitmapSource(), imgM.HasAlpha);
var ext = Path.GetExtension(srcFilePath);
await SaveAsBase64Async(wicSrc, ext, destFilePath, null, token);
return;
}
}
var srcExt = Path.GetExtension(srcFilePath).ToLowerInvariant();
var mimeType = BHelper.GetMIMEType(srcExt);
try
{
token.ThrowIfCancellationRequested();
// for basic MIME formats
if (!string.IsNullOrEmpty(mimeType))
{
// read source file content
using var fs = new FileStream(srcFilePath, FileMode.Open, FileAccess.Read);
var data = new byte[fs.Length];
await fs.ReadExactlyAsync(data.AsMemory(0, (int)fs.Length), token);
fs.Close();
token.ThrowIfCancellationRequested();
// convert bitmap to base64
var header = $"data:{mimeType};base64,";
var base64 = Convert.ToBase64String(data);
token.ThrowIfCancellationRequested();
// write base64 file
using var sw = new StreamWriter(destFilePath);
await sw.WriteAsync(header + base64);
await sw.FlushAsync(token).ConfigureAwait(false);
sw.Close();
return;
}
// for not supported formats
var bmp = await LoadAsync(srcFilePath, readOptions, transform, token);
await SaveAsBase64Async(bmp.Image, srcExt, destFilePath, null, token);
}
catch (OperationCanceledException) { }
}
/// <summary>
/// Applies changes from <see cref="ImgTransform"/>.
/// </summary>
public static WicBitmapSource? TransformImage(WicBitmapSource? bmpSrc, ImgTransform? transform)
{
if (bmpSrc == null || transform == null) return bmpSrc;
// list of flips
var flips = new List<WICBitmapTransformOptions>();
if (transform.Flips.HasFlag(FlipOptions.Horizontal))
{
flips.Add(WICBitmapTransformOptions.WICBitmapTransformFlipHorizontal);
}
if (transform.Flips.HasFlag(FlipOptions.Vertical))
{
flips.Add(WICBitmapTransformOptions.WICBitmapTransformFlipVertical);
}
// apply flips
foreach (var flip in flips)
{
bmpSrc.FlipRotate(flip);
}
// rotate
var rotate = transform.Rotation switch
{
90 => WICBitmapTransformOptions.WICBitmapTransformRotate90,
-270 => WICBitmapTransformOptions.WICBitmapTransformRotate90,
-90 => WICBitmapTransformOptions.WICBitmapTransformRotate270,
270 => WICBitmapTransformOptions.WICBitmapTransformRotate270,
180 => WICBitmapTransformOptions.WICBitmapTransformRotate180,
-180 => WICBitmapTransformOptions.WICBitmapTransformRotate180,
_ => WICBitmapTransformOptions.WICBitmapTransformRotate0,
};
if (rotate != WICBitmapTransformOptions.WICBitmapTransformRotate0)
{
bmpSrc.FlipRotate(rotate);
}
// invert color
if (transform.IsColorInverted)
{
var newBmp = new WicBitmapSource(
bmpSrc.Width, bmpSrc.Height,
WicPixelFormat.GUID_WICPixelFormat32bppPRGBA);
using var dc = newBmp.CreateDeviceContext();
using var effect = dc.CreateEffect(Direct2DEffects.CLSID_D2D1Invert);
using var cb = dc.CreateBitmapFromWicBitmap(bmpSrc.ComObject);
{
effect.SetInput(cb, 0);
dc.BeginDraw();
dc.DrawImage(effect);
dc.EndDraw();
}
bmpSrc.Dispose();
bmpSrc = newBmp;
}
return bmpSrc;
}
/// <summary>
/// Initialize Magick.NET.
/// </summary>
public static void InitMagickNET()
{
OpenCL.IsEnabled = true;
ResourceLimits.LimitMemory(new Percentage(75));
}
/// <summary>
/// Checks if the supplied file name is supported for lossless compression using Magick.NET.
/// </summary>
public static bool IsLosslessCompressSupported(string? filePath)
{
var opt = new ImageOptimizer()
{
OptimalCompression = true,
};
return opt.IsSupported(filePath);
}
/// <summary>
/// Performs lossless compression on the specified file using Magick.NET.
/// If the new file size is not smaller, the file won't be overwritten.
/// </summary>
/// <returns>True when the image could be compressed otherwise false.</returns>
/// <exception cref="NotSupportedException"></exception>
public static bool LosslessCompress(string? filePath)
{
if (string.IsNullOrWhiteSpace(filePath)) return false;
var fi = new FileInfo(filePath);
var opt = new ImageOptimizer()
{
OptimalCompression = true,
};
// check if the format is supported
if (!opt.IsSupported(fi)) throw new NotSupportedException("IGE_002: Unsupported image format.");
return opt.LosslessCompress(fi);
}
#endregion // Public functions
#region Private functions
/// <summary>
/// Checks if the image data is animated format.
/// </summary>
/// <param name="imgC"></param>
/// <param name="ext">File extension, e.g: <c>.gif</c></param>
private static bool CheckAnimatedFormat(MagickImageCollection imgC, string? ext)
{
var isAnimatedExtension = ext == ".GIF" || ext == ".GIFV" || ext == ".WEBP" || ext == ".JXL";
var canAnimate = imgC.Count > 1
&& (isAnimatedExtension || imgC.Any(i => i.GifDisposeMethod != GifDisposeMethod.Undefined));
return canAnimate;
}
/// <summary>
/// Read image file using stream
/// </summary>
private static (bool loadSuccessful, IgImgData result, string ext, MagickReadSettings settings) ReadWithStream(string filePath, CodecReadOptions? options = null, ImgTransform? transform = null, IgMetadata? metadata = null)
{
options ??= new();
var loadSuccessful = true;
metadata ??= LoadMetadata(filePath, options);
var ext = Path.GetExtension(filePath).ToUpperInvariant();
var settings = ParseSettings(options, false, filePath);
var result = new IgImgData()
{
FrameCount = metadata?.FrameCount ?? 0,
HasAlpha = metadata?.HasAlpha ?? false,
CanAnimate = metadata?.CanAnimate ?? false,
};
#region Read image data
switch (ext)
{
case ".TXT": // base64 string
case ".B64":
var base64Content = string.Empty;
using (var fs = new StreamReader(filePath))
{
base64Content = fs.ReadToEnd();
}
if (result.CanAnimate)
{
result.Source = BHelper.ToGdiPlusBitmapFromBase64(base64Content);
}
else
{
result.Image = BHelper.ToWicBitmapSource(base64Content);
if (result.FrameCount == 1)
{
result.Image = TransformImage(result.Image, transform);
}
}
break;
case ".GIF":
case ".GIFV":
case ".FAX":
try
{
// Note: Using WIC is much faster than using MagickImageCollection
if (result.CanAnimate)
{
result.Source = BHelper.ToGdiPlusBitmap(filePath);
}
// multiple frame
else if (result.FrameCount > 0)
{
result.Source = WicBitmapDecoder.Load(filePath);
}
// single frame
else
{
result.Image = WicBitmapSource.Load(filePath);
}
}
catch
{
loadSuccessful = false;
}
break;
case ".WEBP":
try
{
using var webp = new WebPWrapper();
if (result.CanAnimate)
{
var aniWebP = webp.AnimLoad(filePath);
var frames = aniWebP.Select(frame =>
{
var duration = frame.Duration > 0 ? frame.Duration : 100;
return new AnimatedImgFrame(frame.Bitmap, (uint)duration);
});
result.Source = new AnimatedImg(frames, result.FrameCount);
}
else
{
using var webpBmp = webp.Load(filePath);
result.Image = BHelper.ToWicBitmapSource(webpBmp);
}
}
catch
{
loadSuccessful = false;
}
break;
case ".JXR":
case ".HDP":
case ".WDP":
try
{
var wic = WicBitmapSource.Load(filePath);
if (options.IgnoreColorProfile)
{
result.Image = wic;
}
else
{
var ms = BHelper.ToMemoryStream(wic);
var imgM = new MagickImage(ms);
var profiles = GetProfiles(imgM);
var thumbM = ProcessMagickImageAndReturnThumbnail(imgM, options, ext, true, profiles.ColorProfile, profiles.ExifProfile);
if (thumbM != null)
{
imgM?.Dispose();
imgM = thumbM;
}
// apply final changes
TransformImage(imgM, transform);
result.Image = BHelper.ToWicBitmapSource(imgM.ToBitmapSource());
}
}
catch
{
loadSuccessful = false;
}
break;
default:
loadSuccessful = false;
break;
}
#endregion
// apply size setting
if (options.Width > 0 && options.Height > 0)
{
using var imgM = new MagickImage();
if (result.Image != null)
{
if (result.Image.Width > options.Width || result.Image.Height > options.Height)
{
imgM.Read(result.Image.CopyPixels(0, 0, result.Image.Width, result.Image.Height));
ApplySizeSettings(imgM, options);