forked from arduano/ImageToMidi
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageProcessing.cs
More file actions
1655 lines (1468 loc) · 65.5 KB
/
ImageProcessing.cs
File metadata and controls
1655 lines (1468 loc) · 65.5 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
/*using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
namespace ImageToMidi
{
/// <summary>
/// 图像处理管理器,负责所有图像加载、处理和转换相关功能
/// </summary>
public class ImageProcessing
{
private readonly MainWindow mainWindow;
// 图像数据缓存
public BitmapSource OpenedImageSrc { get; set; }
public byte[] OpenedImagePixels { get; set; }
public BitmapSource OriginalImageSrc { get; set; }
public BitmapSource LandscapeColorPreviewSrc { get; set; }
public byte[] LandscapeColorPreviewPixels { get; set; }
public BitmapSource PortraitColorPreviewSrc { get; set; }
public byte[] PortraitColorPreviewPixels { get; set; }
public BitmapSource LandscapeGrayPreviewSrc { get; set; }
public byte[] LandscapeGrayPreviewPixels { get; set; }
public BitmapSource PortraitGrayPreviewSrc { get; set; }
public byte[] PortraitGrayPreviewPixels { get; set; }
public byte[] DitheredImagePixels { get; set; }
// 图像属性
public int OpenedImageWidth { get; set; }
public int OpenedImageHeight { get; set; }
public string OpenedImagePath { get; set; } = "";
public int OriginalImageWidth { get; set; }
public int OriginalImageHeight { get; set; }
// 预览旋转角度和镜像状态
public int PreviewRotation { get; set; } = 0; // 0, 90, 180, 270
public bool PreviewFlip { get; set; } = false;
// 动画帧相关
private List<BitmapFrame> animatedFrames = null;
private int currentFrameIndex = 0;
private int totalFrameCount = 0;
private bool isAnimatedImage = false;
public ImageProcessing(MainWindow window)
{
mainWindow = window ?? throw new ArgumentNullException(nameof(window));
}
/// <summary>
/// 支持的文件扩展名定义
/// </summary>
public static class SupportedExtensions
{
public static readonly string[] BitmapAllowed = { ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".webp" };
public static readonly string[] VectorAllowed = { ".svg" };
public static readonly string[] GsVectorAllowed = { ".eps", ".ai", ".pdf" };
public static readonly string[] AllSupported = BitmapAllowed.Concat(VectorAllowed).Concat(GsVectorAllowed).ToArray();
}
/// <summary>
/// 判断文件是否为受支持的图片格式
/// </summary>
public static bool IsSupportedImageFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
return false;
string ext = Path.GetExtension(filePath).ToLowerInvariant();
return SupportedExtensions.AllSupported.Contains(ext);
}
/// <summary>
/// 获取文件类型
/// </summary>
public static string GetImageFileType(string filePath)
{
if (string.IsNullOrEmpty(filePath))
return "unknown";
string ext = Path.GetExtension(filePath).ToLowerInvariant();
if (SupportedExtensions.BitmapAllowed.Contains(ext))
return "bitmap";
else if (SupportedExtensions.VectorAllowed.Contains(ext))
return "svg";
else if (SupportedExtensions.GsVectorAllowed.Contains(ext))
return "gsvector";
else
return "unknown";
}
/// <summary>
/// 清理所有图像缓存数据
/// </summary>
public void ClearImageCache()
{
// 清理ZoomableImage资源
if (mainWindow.openedImage != null)
{
mainWindow.openedImage.Source = null;
mainWindow.openedImage.SetSKBitmap(null);
}
// 阶段1:清理最大的像素数组
OpenedImagePixels = null;
DitheredImagePixels = null;
ForceGarbageCollection(); // 立即回收大数组
// 阶段2:清理预览像素数组
LandscapeColorPreviewPixels = null;
LandscapeGrayPreviewPixels = null;
PortraitColorPreviewPixels = null;
PortraitGrayPreviewPixels = null;
ForceGarbageCollection(); // 立即回收预览数组
// 阶段3:清理BitmapSource对象
OpenedImageSrc = null;
OriginalImageSrc = null;
LandscapeColorPreviewSrc = null;
LandscapeGrayPreviewSrc = null;
PortraitColorPreviewSrc = null;
PortraitGrayPreviewSrc = null;
// 阶段4:清理其他对象
mainWindow.chosenPalette = null;
if (mainWindow.convert != null)
{
mainWindow.convert.Cancel();
mainWindow.convert = null;
}
if (mainWindow.genImage != null)
mainWindow.genImage.Source = null;
// 重置属性
OpenedImageWidth = 0;
OpenedImageHeight = 0;
OpenedImagePath = "";
OriginalImageWidth = 0;
OriginalImageHeight = 0;
PreviewRotation = 0;
PreviewFlip = false;
if (mainWindow.openedImage != null)
{
mainWindow.openedImage.ImageRotation = 0;
mainWindow.openedImage.ImageFlip = false;
}
// 清理调色板
mainWindow.colPicker?.ClearPalette();
// 最终强制垃圾回收
ForceGarbageCollection();
}
/// <summary>
/// 强制垃圾回收
/// </summary>
public static void ForceGarbageCollection()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
/// <summary>
/// 通用的图像加载和处理方法
/// </summary>
public async Task LoadImageCommonAsync(string imagePath, bool isFromBrowse)
{
if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
return;
// 设置路径
OpenedImagePath = imagePath;
// 清理所有缓存
ClearImageCache();
// 禁用保存按钮
mainWindow.saveMidi.IsEnabled = false;
var progress = new Progress<string>(msg => mainWindow.saveMidi.Content = msg);
try
{
// 创建处理配置
var config = new ImageProcessingConfig
{
KeyWidth = (int)mainWindow.lastKeyNumber.Value - (int)mainWindow.firstKeyNumber.Value + 1,
TargetHeight = GetTargetHeight(),
PreviewRotation = PreviewRotation,
PreviewFlip = PreviewFlip,
HighResPreviewWidth = mainWindow.highResPreviewWidth,
IsForPreview = !isFromBrowse
};
// 加载和处理图像
var result = await LoadAndProcessImageAsync(imagePath, config, progress);
// 应用结果到主窗口
await ApplyImageLoadResult(result, isFromBrowse, progress);
// 后续处理
await PostLoadProcessing(result, isFromBrowse);
}
catch (Exception ex)
{
await HandleLoadError(ex, imagePath);
return;
}
// 验证文件格式支持
if (!IsSupportedImageFile(imagePath))
{
MessageBox.Show("请选择有效的图片或矢量图文件(png, jpg, jpeg, bmp, gif, webp, svg, eps, ai, pdf)。", "文件类型不支持", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 最终处理
mainWindow.CustomHeightNumberSelect.Value = GetTargetHeight();
mainWindow.saveMidi.Content = $"{Languages.Strings.CS_GeneratingPalette} 0%";
await mainWindow.ReloadAutoPalette();
// 处理灰度模式
await HandleGrayScaleMode();
// 垃圾回收
ForceGarbageCollection();
}
/// <summary>
/// 图像处理的配置参数
/// </summary>
public class ImageProcessingConfig
{
public int KeyWidth { get; set; }
public int TargetHeight { get; set; }
public int PreviewRotation { get; set; } = 0;
public bool PreviewFlip { get; set; } = false;
public int HighResPreviewWidth { get; set; } = 4096;
public bool IsForPreview { get; set; } = false;
}
/// <summary>
/// 图像加载的结果
/// </summary>
public class ImageLoadResult
{
public BitmapSource OriginalSource { get; set; }
public BitmapSource OpenedImageSource { get; set; }
public byte[] OpenedImagePixels { get; set; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public int OriginalImageWidth { get; set; }
public int OriginalImageHeight { get; set; }
public BitmapSource LandscapeColorPreviewSrc { get; set; }
public byte[] LandscapeColorPreviewPixels { get; set; }
public BitmapSource PortraitColorPreviewSrc { get; set; }
public byte[] PortraitColorPreviewPixels { get; set; }
}
/// <summary>
/// 加载和处理图像的核心方法
/// </summary>
public async Task<ImageLoadResult> LoadAndProcessImageAsync(string imagePath, ImageProcessingConfig config, IProgress<string> progress = null)
{
if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
throw new FileNotFoundException($"图像文件不存在: {imagePath}");
var result = new ImageLoadResult();
string fileType = GetImageFileType(imagePath);
BitmapSource src = null;
progress?.Report("正在加载图像...");
switch (fileType)
{
case "bitmap":
src = await LoadBitmapImageAsync(imagePath, progress);
result.OriginalSource = src;
// 生成缩略图
await GenerateThumbnailsAsync(src, result, progress);
break;
case "svg":
src = await LoadSvgImageAsync(imagePath, config, progress);
result.LandscapeColorPreviewSrc = src;
// 修复:创建临时变量
byte[] tempPixels;
ExtractPixels(src, out tempPixels);
result.LandscapeColorPreviewPixels = tempPixels;
break;
case "gsvector":
if (!IsGhostscriptAvailable())
throw new InvalidOperationException("Ghostscript不可用,无法处理EPS/AI/PDF文件");
src = await LoadGsVectorImageAsync(imagePath, config, progress);
break;
default:
throw new NotSupportedException($"不支持的文件格式: {Path.GetExtension(imagePath)}");
}
// 设置基本属性
if (src != null)
{
result.ImageWidth = src.PixelWidth;
result.ImageHeight = src.PixelHeight;
result.OriginalImageWidth = src.PixelWidth;
result.OriginalImageHeight = src.PixelHeight;
result.OpenedImageSource = src;
// 修复:创建临时变量
byte[] tempPixels2;
ExtractPixels(src, out tempPixels2);
result.OpenedImagePixels = tempPixels2;
}
progress?.Report("图像加载完成");
return result;
}
/// <summary>
/// 加载位图图像
/// </summary>
private async Task<BitmapSource> LoadBitmapImageAsync(string path, IProgress<string> progress = null)
{
string ext = Path.GetExtension(path).ToLowerInvariant();
// 特殊处理GIF和WEBP文件
if (ext == ".gif" || ext == ".webp")
{
return await LoadAnimatedImageWithComposition(path, progress);
}
else
{
return await Application.Current.Dispatcher.InvokeAsync(() =>
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.StreamSource = fs;
bmp.EndInit();
bmp.Freeze();
return (BitmapSource)bmp;
}
});
}
}
/// <summary>
/// 加载SVG图像
/// </summary>
private async Task<BitmapSource> LoadSvgImageAsync(string path, ImageProcessingConfig config, IProgress<string> progress = null)
{
return await Task.Run(() =>
{
progress?.Report("正在渲染SVG...");
var svgDocument = Svg.SvgDocument.Open(path);
if (svgDocument == null)
throw new Exception("SVG文件解析失败");
var viewBox = svgDocument.ViewBox;
float viewBoxX = viewBox.MinX;
float viewBoxY = viewBox.MinY;
float viewBoxWidth = viewBox.Width > 0 ? viewBox.Width : 1f;
float viewBoxHeight = viewBox.Height > 0 ? viewBox.Height : 1f;
using (var bitmap = new Bitmap(config.KeyWidth, config.TargetHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
using (var graphics = Graphics.FromImage(bitmap))
{
// 设置高质量渲染选项
graphics.SmoothingMode = SmoothingMode.None;
graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
graphics.PixelOffsetMode = PixelOffsetMode.None;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
// 应用变换
graphics.TranslateTransform(-viewBoxX, -viewBoxY);
graphics.ScaleTransform((float)config.KeyWidth / viewBoxWidth, (float)config.TargetHeight / viewBoxHeight);
// 应用旋转和镜像
if (config.PreviewRotation != 0 || config.PreviewFlip)
{
graphics.TranslateTransform(viewBoxWidth / 2f, viewBoxHeight / 2f);
if (config.PreviewRotation != 0)
graphics.RotateTransform(config.PreviewRotation);
if (config.PreviewFlip)
graphics.ScaleTransform(-1, 1);
graphics.TranslateTransform(-viewBoxWidth / 2f, -viewBoxHeight / 2f);
}
// 渲染SVG
svgDocument.Draw(graphics);
// 转换为WPF BitmapSource
var bitmapSource = ConvertBitmapToBitmapSource(bitmap);
bitmapSource.Freeze();
return bitmapSource;
}
});
}
/// <summary>
/// 加载Ghostscript矢量图像
/// </summary>
private async Task<BitmapSource> LoadGsVectorImageAsync(string path, ImageProcessingConfig config, IProgress<string> progress = null)
{
return await Task.Run(() =>
{
progress?.Report("正在使用Ghostscript渲染...");
return RenderGsVectorToBitmapSource(path, config.KeyWidth, config.TargetHeight, progress);
});
}
/// <summary>
/// 将图像加载结果应用到主窗口
/// </summary>
private async Task ApplyImageLoadResult(ImageLoadResult result, bool isFromBrowse, IProgress<string> progress)
{
if (result?.OpenedImageSource == null)
return;
// 直接更新 ImageProcessing 中的数据,MainWindow 通过属性访问器自动获取
OriginalImageSrc = result.OriginalSource;
OpenedImageSrc = result.OpenedImageSource;
OpenedImagePixels = result.OpenedImagePixels;
OpenedImageWidth = result.ImageWidth;
OpenedImageHeight = result.ImageHeight;
OriginalImageWidth = result.OriginalImageWidth;
OriginalImageHeight = result.OriginalImageHeight;
// 更新预览缓存
LandscapeColorPreviewSrc = result.LandscapeColorPreviewSrc;
LandscapeColorPreviewPixels = result.LandscapeColorPreviewPixels;
PortraitColorPreviewSrc = result.PortraitColorPreviewSrc;
PortraitColorPreviewPixels = result.PortraitColorPreviewPixels;
// ============ 删除重复的同步代码 ============
// 以下代码全部删除,因为 MainWindow 现在通过属性访问器直接访问 ImageProcessing 的数据
/*
mainWindow.openedImageSrc = OpenedImageSrc;
mainWindow.openedImagePixels = OpenedImagePixels;
mainWindow.originalImageSrc = OriginalImageSrc;
mainWindow.openedImageWidth = OpenedImageWidth;
mainWindow.openedImageHeight = OpenedImageHeight;
mainWindow.originalImageWidth = OriginalImageWidth;
mainWindow.originalImageHeight = OriginalImageHeight;
mainWindow.landscapeColorPreviewSrc = LandscapeColorPreviewSrc;
mainWindow.landscapeColorPreviewPixels = LandscapeColorPreviewPixels;
mainWindow.portraitColorPreviewSrc = PortraitColorPreviewSrc;
mainWindow.portraitColorPreviewPixels = PortraitColorPreviewPixels;
// 特殊处理不同的图像类型
string fileType = GetImageFileType(OpenedImagePath);
switch (fileType)
{
case "bitmap":
await HandleBitmapResult(result, isFromBrowse);
break;
case "svg":
await HandleSvgResult(result, isFromBrowse);
break;
case "gsvector":
await HandleGsVectorResult(result, isFromBrowse, progress);
break;
}
}
/// <summary>
/// 处理位图加载结果
/// </summary>
private async Task HandleBitmapResult(ImageLoadResult result, bool isFromBrowse)
{
if (isFromBrowse && OriginalImageSrc != null)
{
mainWindow.openedImage.Opacity = 0;
var skBitmap = OriginalImageSrc.ToSKBitmap();
OriginalImageSrc = null; // 释放原始引用
mainWindow.openedImage.SetSKBitmap(skBitmap);
var fadeIn = (Storyboard)mainWindow.openedImage.GetValue(MainWindow.FadeInStoryboard);
fadeIn?.Begin();
// 检测并加载动图帧
LoadAnimatedFrames(OpenedImagePath);
await mainWindow.Dispatcher.BeginInvoke(new Action(() =>
{
ForceGarbageCollection();
}), System.Windows.Threading.DispatcherPriority.ContextIdle);
}
else if (!isFromBrowse)
{
await UpdateOpenedImageByAngleAndFlip();
mainWindow.openedImage.Source = OriginalImageSrc;
LoadAnimatedFrames(OpenedImagePath);
}
}
/// <summary>
/// 处理SVG加载结果
/// </summary>
private async Task HandleSvgResult(ImageLoadResult result, bool isFromBrowse)
{
if (isFromBrowse)
{
var settings = new SharpVectors.Renderers.Wpf.WpfDrawingSettings();
var reader = new SharpVectors.Converters.FileSvgReader(settings);
var drawing = reader.Read(OpenedImagePath);
if (drawing != null)
{
mainWindow.openedImage.SvgDrawing = drawing;
}
else
{
MessageBox.Show("SVG加载失败。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (OpenedImageSrc != null)
{
var skBitmap = OpenedImageSrc.ToSKBitmap();
mainWindow.openedImage.SetSKBitmap(skBitmap);
}
}
else
{
mainWindow.openedImage.Source = OpenedImageSrc;
}
}
/// <summary>
/// 处理Ghostscript矢量图加载结果
/// </summary>
private async Task HandleGsVectorResult(ImageLoadResult result, bool isFromBrowse, IProgress<string> progress)
{
if (isFromBrowse)
{
try
{
var highResBitmap = await RenderGsVectorHighResPreview(OpenedImagePath, OpenedImageSrc, mainWindow.highResPreviewWidth, progress);
var skBitmap = highResBitmap.ToSKBitmap();
mainWindow.openedImage.SetSKBitmap(skBitmap);
}
catch
{
if (OpenedImageSrc != null)
{
var skBitmap = OpenedImageSrc.ToSKBitmap();
mainWindow.openedImage.SetSKBitmap(skBitmap);
}
}
}
else
{
try
{
var highResBitmap = await RenderGsVectorHighResPreview(OpenedImagePath, OpenedImageSrc, mainWindow.highResPreviewWidth, progress);
mainWindow.openedImage.Source = highResBitmap;
}
catch
{
mainWindow.openedImage.Source = OpenedImageSrc;
}
}
}
/// <summary>
/// 加载后的后续处理
/// </summary>
private async Task PostLoadProcessing(ImageLoadResult result, bool isFromBrowse)
{
// 如果是从浏览按钮加载,添加到批量列表
if (isFromBrowse && (OriginalImageSrc != null || OpenedImageSrc != null))
{
var eitherSrc = OriginalImageSrc ?? OpenedImageSrc;
mainWindow.BatchFileList.Add(new BatchFileItem
{
Index = mainWindow.BatchFileList.Count + 1,
Format = Path.GetExtension(OpenedImagePath).TrimStart('.').ToUpperInvariant(),
FileName = Path.GetFileName(OpenedImagePath),
FrameCount = 1,
Resolution = $"{eitherSrc.PixelWidth}x{eitherSrc.PixelHeight}",
FullPath = OpenedImagePath
});
}
else if (isFromBrowse)
{
MessageBox.Show("图片加载失败,无法添加到批量列表。", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// 处理加载错误
/// </summary>
private async Task HandleLoadError(Exception ex, string imagePath)
{
string fileType = GetImageFileType(imagePath);
if (fileType == "gsvector" && !IsGhostscriptAvailable())
{
ShowGhostscriptDownloadDialog();
}
else
{
string ext = Path.GetExtension(imagePath).ToUpperInvariant();
MessageBox.Show($"{ext}加载失败:" + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// 处理灰度模式
/// </summary>
public async Task HandleGrayScaleMode()
{
if (mainWindow.grayScaleCheckBox.IsChecked == true)
{
if (LandscapeColorPreviewSrc != null && LandscapeGrayPreviewSrc == null)
{
LandscapeGrayPreviewSrc = ToGrayScale(LandscapeColorPreviewSrc);
ExtractPixels(LandscapeGrayPreviewSrc, out var pixels);
LandscapeGrayPreviewPixels = pixels;
// 删除重复同步代码:mainWindow.landscapeGrayPreviewSrc = LandscapeGrayPreviewSrc;
}
if (PortraitColorPreviewSrc != null && PortraitGrayPreviewSrc == null)
{
PortraitGrayPreviewSrc = ToGrayScale(PortraitColorPreviewSrc);
ExtractPixels(PortraitGrayPreviewSrc, out var pixels);
PortraitGrayPreviewPixels = pixels;
// 删除重复同步代码:mainWindow.portraitGrayPreviewSrc = PortraitGrayPreviewSrc;
}
await UpdateOpenedImageByAngleAndFlip();
}
}
// 获取目标高度
public int GetTargetHeight()
{
int effectiveWidth = mainWindow.GetEffectiveKeyWidth();
switch (mainWindow.heightMode)
{
case MainWindow.HeightModeEnum.SameAsWidth:
return effectiveWidth;
case MainWindow.HeightModeEnum.OriginalHeight:
return OpenedImageHeight;
case MainWindow.HeightModeEnum.CustomHeight:
return mainWindow.customHeight;
case MainWindow.HeightModeEnum.OriginalAspectRatio:
if (OpenedImageSrc == null)
{
return 0;
}
if (PreviewRotation == 90 || PreviewRotation == 270)
{
double aspectRatio = (double)OriginalImageWidth / OriginalImageHeight;
return (int)(effectiveWidth * aspectRatio);
}
else
{
double aspectRatio = (double)OriginalImageHeight / OriginalImageWidth;
return (int)(effectiveWidth * aspectRatio);
}
default:
return OriginalImageSrc != null ? OriginalImageHeight : OpenedImageHeight;
}
}
// ======== 以下是辅助方法,从原MainWindow中移动过来的 ========
/// <summary>
/// 生成缩略图
/// </summary>
private async Task GenerateThumbnailsAsync(BitmapSource src, ImageLoadResult result, IProgress<string> progress = null)
{
await Task.Run(() =>
{
progress?.Report("正在生成横向缩略图...");
var landscapeColor = Downsample(src, null, 256);
ExtractPixels(landscapeColor, out var landscapeColorPixels);
progress?.Report("正在生成纵向缩略图...");
var portraitColor = Downsample(src, 256, null);
ExtractPixels(portraitColor, out var portraitColorPixels);
result.LandscapeColorPreviewSrc = landscapeColor;
result.LandscapeColorPreviewPixels = landscapeColorPixels;
result.PortraitColorPreviewSrc = portraitColor;
result.PortraitColorPreviewPixels = portraitColorPixels;
});
}
/// <summary>
/// 图像缩放方法
/// </summary>
public BitmapSource Downsample(BitmapSource src, int? maxWidth = null, int? maxHeight = null, Action<double> progress = null)
{
int width = src.PixelWidth;
int height = src.PixelHeight;
double scaleX = 1.0, scaleY = 1.0;
if (maxWidth.HasValue && width > maxWidth.Value)
scaleX = (double)maxWidth.Value / width;
if (maxHeight.HasValue && height > maxHeight.Value)
scaleY = (double)maxHeight.Value / height;
if (scaleX == 1.0 && scaleY == 1.0)
return src;
int dstW = (int)Math.Round(width * scaleX);
int dstH = (int)Math.Round(height * scaleY);
var src32 = new FormatConvertedBitmap(src, PixelFormats.Bgra32, null, 0);
src32.Freeze();
int srcStride = width * 4;
int srcSize = height * srcStride;
int dstSize = dstH * dstW * 4;
byte[] srcPixels = new byte[srcSize];
byte[] dstPixels = new byte[dstSize];
Array.Clear(dstPixels, 0, dstSize);
src32.CopyPixels(srcPixels, srcStride, 0);
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount / 2)
};
System.Threading.Tasks.Parallel.For(0, dstH, parallelOptions, y =>
{
ProcessRow(y, dstW, dstH, width, height, srcPixels, dstPixels, srcStride, progress);
});
var bmp = BitmapSource.Create(dstW, dstH, src.DpiX, src.DpiY, PixelFormats.Bgra32, null, dstPixels, dstW * 4);
bmp.Freeze();
return bmp;
}
/// <summary>
/// 处理缩放的单行像素
/// </summary>
private static void ProcessRow(int y, int dstW, int dstH, int width, int height,
byte[] srcPixels, byte[] dstPixels, int srcStride, Action<double> progress)
{
for (int x = 0; x < dstW; x++)
{
double srcX0 = x / (double)dstW * width;
double srcX1 = (x + 1) / (double)dstW * width;
double srcY0 = y / (double)dstH * height;
double srcY1 = (y + 1) / (double)dstH * height;
int ix0 = (int)Math.Floor(srcX0);
int ix1 = (int)Math.Min(Math.Ceiling(srcX1), width);
int iy0 = (int)Math.Floor(srcY0);
int iy1 = (int)Math.Min(Math.Ceiling(srcY1), height);
long b = 0, g = 0, r = 0, a = 0, cnt = 0;
for (int sy = iy0; sy < iy1; sy++)
{
for (int sx = ix0; sx < ix1; sx++)
{
int idx = sy * srcStride + sx * 4;
b += srcPixels[idx + 0];
g += srcPixels[idx + 1];
r += srcPixels[idx + 2];
a += srcPixels[idx + 3];
cnt++;
}
}
int didx = y * dstW * 4 + x * 4;
if (cnt > 0)
{
dstPixels[didx + 0] = (byte)(b / cnt);
dstPixels[didx + 1] = (byte)(g / cnt);
dstPixels[didx + 2] = (byte)(r / cnt);
dstPixels[didx + 3] = (byte)(a / cnt);
}
}
if (progress != null && (y % 8 == 0 || y == dstH - 1))
{
progress((y + 1) / (double)dstH);
}
}
/// <summary>
/// 提取像素数据
/// </summary>
public static void ExtractPixels(BitmapSource source, out byte[] pixels)
{
int w = source.PixelWidth;
int h = source.PixelHeight;
int stride = source.Format.BitsPerPixel / 8 * w;
pixels = new byte[h * stride];
source.CopyPixels(pixels, stride, 0);
}
/// <summary>
/// 转换为灰度图像
/// </summary>
public static BitmapSource ToGrayScale(BitmapSource src, IProgress<double> progress = null)
{
var format = PixelFormats.Bgra32;
int width = src.PixelWidth;
int height = src.PixelHeight;
int stride = width * 4;
byte[] pixels = new byte[height * stride];
src.CopyPixels(pixels, stride, 0);
for (int y = 0; y < height; y++)
{
int rowStart = y * stride;
for (int x = 0; x < width; x++)
{
int i = rowStart + x * 4;
byte b = pixels[i];
byte g = pixels[i + 1];
byte r = pixels[i + 2];
byte gray = (byte)(0.299 * r + 0.587 * g + 0.114 * b);
pixels[i] = gray;
pixels[i + 1] = gray;
pixels[i + 2] = gray;
}
if (progress != null && (y % 8 == 0 || y == height - 1))
progress.Report((y + 1) / (double)height); // 使用 Report 方法
}
var bmp = BitmapSource.Create(width, height, src.DpiX, src.DpiY, format, null, pixels, stride);
bmp.Freeze();
return bmp;
}
/// <summary>
/// 处理动画图像的帧合成
/// </summary>
private async Task<BitmapSource> LoadAnimatedImageWithComposition(string path, IProgress<string> progress = null)
{
return await Task.Run(() =>
{
return Application.Current.Dispatcher.Invoke(() =>
{
try
{
progress?.Report("正在解码动画帧...");
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var decoder = BitmapDecoder.Create(fs,
BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile,
BitmapCacheOption.OnLoad);
if (decoder.Frames.Count == 0)
return LoadWithDefaultMethod(path);
var firstFrame = decoder.Frames[0];
// 修复:对于动画图像,只返回第一帧,不进行多帧合成
// 这样可以确保总是显示第一帧而不是第10帧
progress?.Report($"检测到{decoder.Frames.Count}帧,使用第一帧");
return ProcessFrameFormat(firstFrame);
}
}
catch (Exception ex)
{
progress?.Report($"动画加载失败:{ex.Message},使用默认方式");
return LoadWithDefaultMethod(path);
}
});
});
}
// 继续添加其他辅助方法...
// (由于字符限制,我将在下一个代码块中继续)
/// <summary>
/// 处理单帧格式
/// </summary>
private static BitmapSource ProcessFrameFormat(BitmapSource frame)
{
try
{
var originalFormat = frame.Format;
if (originalFormat == PixelFormats.Indexed8 ||
originalFormat == PixelFormats.Indexed4 ||
originalFormat == PixelFormats.Indexed2 ||
originalFormat == PixelFormats.Indexed1)
{
return PreserveIndexedColors(frame);
}
else
{
var converted = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, null, 0);
converted.Freeze();
return converted;
}
}
catch
{
var converted = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, null, 0);
converted.Freeze();
return converted;
}
}
/// <summary>
/// 保持索引颜色的精度
/// </summary>
private static BitmapSource PreserveIndexedColors(BitmapSource indexedFrame)
{
try
{
int width = indexedFrame.PixelWidth;
int height = indexedFrame.PixelHeight;
var palette = indexedFrame.Palette;
if (palette == null || palette.Colors.Count == 0)
{
var converted = new FormatConvertedBitmap(indexedFrame, PixelFormats.Bgra32, null, 0);
converted.Freeze();
return converted;
}
int stride = (width * indexedFrame.Format.BitsPerPixel + 7) / 8;
byte[] indexedPixels = new byte[height * stride];
indexedFrame.CopyPixels(indexedPixels, stride, 0);
int outputStride = width * 4;
byte[] outputPixels = new byte[height * outputStride];
int bitsPerPixel = indexedFrame.Format.BitsPerPixel;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int colorIndex = GetColorIndex(indexedPixels, x, y, width, bitsPerPixel, stride);
if (colorIndex < palette.Colors.Count)
{
var color = palette.Colors[colorIndex];
int outputIndex = y * outputStride + x * 4;
outputPixels[outputIndex] = color.B;
outputPixels[outputIndex + 1] = color.G;
outputPixels[outputIndex + 2] = color.R;
outputPixels[outputIndex + 3] = color.A;
}
}
}
var result = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, outputPixels, outputStride);
result.Freeze();
return result;
}
catch
{
var converted = new FormatConvertedBitmap(indexedFrame, PixelFormats.Bgra32, null, 0);
converted.Freeze();
return converted;
}
}
/// <summary>
/// 从索引像素数据中提取颜色索引
/// </summary>
private static int GetColorIndex(byte[] pixels, int x, int y, int width, int bitsPerPixel, int stride)
{
switch (bitsPerPixel)
{
case 8:
return pixels[y * stride + x];
case 4:
{