-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cs
More file actions
1187 lines (1054 loc) · 51.7 KB
/
Main.cs
File metadata and controls
1187 lines (1054 loc) · 51.7 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.Diagnostics;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Reflection;
using System.Runtime.InteropServices;
using ImageMagick;
using Microsoft.VisualBasic.FileIO; // für Papierkorb-Funktion bei FileSystem.DeleteFile
using Svg;
namespace ImageCropper;
public partial class Main : Form
{
private enum DragHandle // Definition der möglichen Griffpunkte
{
None, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight, Inside
}
private const int HANDLE_SIZE = 16; // Größe der Griffe in Pixeln
private int _handleSize;
private Rectangle _selectionRect = Rectangle.Empty;
private Point _dragStartPoint;
private DragHandle _currentDragHandle = DragHandle.None;
private bool _isDragging;
private string? _currentImagePath;
private Point _mouseDownPoint; // Wo die Taste gedrückt wurde
private bool _isNewSelection; // Unterscheidung: Bestehender Griff vs. neues Rechteck
private bool _isLoading;
private AppSettings _settings; // Kein 'new' hier, da wir es im Konstruktor laden
private float _currentAspectRatio;
private readonly string _settingsPath;
private static readonly string _appPath = AppContext.BaseDirectory; // Sicherer als Application.ExecutablePath in .NET 8+
private static readonly string _helpFilePath = Path.Combine(_appPath, "ImageCropper_Hilfe.pdf");
private readonly string _appName = "ImageCropper";
private const int WM_KEYDOWN = 0x100; // WM_SYSKEYDOWN = 0x104;
private const int WM_KEYUP = 0x101; // WM_SYSKEYUP = 0x105;
private bool _downShift = false; // keeps shift state, s. ProcessKeyCmd, dort wird an/aus geschaltet
public Main(string? bildPfad = null)
{
InitializeComponent(); //DoubleBuffered = true; // im Inspector gesetzt
_handleSize = (int)(HANDLE_SIZE * DeviceDpi / 96.0); // Skalierung für hohe DPI
_settingsPath = GetSettingsPath();
_settings = SettingsManager.Load(_settingsPath);
_currentAspectRatio = _settings.DefaultAspectRatio; // Aktuelles Ratio initialisieren
SetAspectRatio(_currentAspectRatio);
UpdateEditorToolTip();
if (!string.IsNullOrEmpty(bildPfad)) { LoadImageFile(bildPfad); }
}
protected override void OnDpiChanged(DpiChangedEventArgs e)
{
base.OnDpiChanged(e);
_handleSize = (int)(HANDLE_SIZE * e.DeviceDpiNew / 96.0); // Skalierung beim Monitorwechsel neu berechnen
pictureBox.Invalidate(); // Evtl. UI-Elemente neu zeichnen
}
private string GetSettingsPath()
{
var appDir = AppContext.BaseDirectory;
var localSettings = Path.Combine(_appPath, _appName + ".xml");
if (File.Exists(localSettings)) { return localSettings; } // Existiert bereits eine lokale Einstellungsdatei? (typisch für Portable)
if (File.Exists(Path.Combine(appDir, "unins000.exe")))
{
return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), _appName), _appName + ".xml");
}
return localSettings; //// Fallback: Keine Installation erkannt -> Portable Modus (lokal speichern)
}
private void SaveSettings()
{
_settings.LastDirectory = _settings.LastDirectory; // Falls du _lastDirectory noch separat hast, sonst direkt _settings nutzen
SettingsManager.Save(_settings, _settingsPath);
}
private async void LoadImageFile(string imagePath)
{
if (_isLoading) { return; } // Verhindert Mehrfachstarts
try
{
if (!File.Exists(imagePath)) { return; }
_isLoading = true; // "Warten"-Status aktivieren
menuStrip.Enabled = false;
Application.UseWaitCursor = true;
Cursor.Current = Cursors.WaitCursor;
pictureBox.Image = null; // Altes Bild sofort ausblenden
pictureBox.Invalidate(); // Paint-Event erzwingen
var nextImage = await Task.Run<Image>(() => // Bild im Hintergrund laden
{
var extension = Path.GetExtension(imagePath).ToLowerInvariant();
// 1. NEU: SVG-Behandlung
if (extension == ".svg")
{
var svgDocument = SvgDocument.Open(imagePath) ?? throw new Exception("Die SVG-Datei konnte nicht gelesen werden.");
// .Draw() konvertiert die Vektoren nahtlos in ein GDI+ Bitmap
return svgDocument.Draw();
}
// 2. Magick (HEIC, AVIF, etc.)
else if (Utils.RequiresMagick(imagePath))
{
using var magickImage = new MagickImage(imagePath);
magickImage.AutoOrient();
return magickImage.ToBitmap();
}
// 3. Standard-Bilder (JPG, PNG, BMP)
else
{
using var stream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
using var tempImage = Image.FromStream(stream);
Utils.CorrectExifOrientation(tempImage);
return new Bitmap(tempImage);
}
});
_isLoading = false; // UI-Update (zurück im Haupt-Thread)
SuspendLayout();
var oldImage = pictureBox.Image;
pictureBox.Image = nextImage;
oldImage?.Dispose();
_selectionRect = Rectangle.Empty;
AdjustFormSizeToImage(pictureBox.Image);
ResumeLayout(true); // Das zwingt die PictureBox dazu, ihre ClientSize an das neu skalierte Formular anzupassen
if (_settings.AutoSelectionOnLoad) { CreateDefaultSelection(); } // die PictureBox kennt nun ihre finalen Maße
_currentImagePath = imagePath;
standardToolStripMenuItem.Enabled = true;
Text = $"{_appName} - {Path.GetFileName(imagePath)} ({nextImage.Width} × {nextImage.Height} Px)";
}
catch (Exception ex)
{
pictureBox.Invalidate();
Utils.ErrTaskDlg(Handle, ex);
}
finally
{
_isLoading = false;
menuStrip.Enabled = true;
Application.UseWaitCursor = false;
Cursor.Current = Cursors.Default;
}
}
private void CreateDefaultSelection()
{
if (pictureBox.Image is null) { return; }
var validRect = GetImageRectangle();
if (validRect.IsEmpty || validRect.Width <= 0 || validRect.Height <= 0) { return; }
// Wir nehmen 80% der Bildfläche als initialen Rahmen
var w = (int)(validRect.Width * 0.8);
var h = (int)(validRect.Height * 0.8);
var defaultRect = new Rectangle(
validRect.X + (validRect.Width - w) / 2,
validRect.Y + (validRect.Height - h) / 2,
w, h);
// Falls ein festes Ratio (z.B. 1:1 oder 3:4) eingestellt ist, direkt anwenden
if (_currentAspectRatio > 0)
{
ApplyAspectRatio(ref defaultRect, DragHandle.BottomRight);
// Nach der Ratio-Korrektur nochmal sauber zentrieren
defaultRect.X = validRect.X + (validRect.Width - defaultRect.Width) / 2;
defaultRect.Y = validRect.Y + (validRect.Height - defaultRect.Height) / 2;
}
_selectionRect = defaultRect;
// UI-Elemente und Buttons sofort aktivieren
clipContextMenuItem.Enabled = cropContextMenuItem.Enabled =
cancelContextMenuItem.Enabled = cropToolStripMenuItem.Enabled = true;
pictureBox.Invalidate();
}
private void SetAspectRatio(float ratio)
{
_currentAspectRatio = ratio; // Speichert in die nicht-persistente Eigenschaft
ratioFreeToolStripMenuItem.Checked = false;
ratio1to1ToolStripMenuItem.Checked = false;
ratio2to3ToolStripMenuItem.Checked = false;
ratio3to4ToolStripMenuItem.Checked = false;
if (ratio <= 0) { ratioFreeToolStripMenuItem.Checked = true; }
else if (Math.Abs(ratio - 1.0f) < 0.01) { ratio1to1ToolStripMenuItem.Checked = true; }
else if (Math.Abs(ratio - (2f / 3f)) < 0.01) { ratio2to3ToolStripMenuItem.Checked = true; }
else if (Math.Abs(ratio - (3f / 4f)) < 0.01) { ratio3to4ToolStripMenuItem.Checked = true; }
if (!_selectionRect.IsEmpty && ratio > 0)
{
ApplyAspectRatio(ref _selectionRect, DragHandle.BottomRight);
_selectionRect = Utils.NormalizeRectangle(_selectionRect);
}
pictureBox.Invalidate(); // führt auch bei leerer PictureBox zum Aktualisieren der Statusleiste mit den Shortcuts
}
private void ApplyAspectRatio(ref Rectangle rect, DragHandle handle)
{
if (_currentAspectRatio <= 0) { return; }
var right = rect.Right; // Fixpunkte merken
var bottom = rect.Bottom; // für die Verankerung
if ((float)rect.Width / rect.Height > _currentAspectRatio) // Breiter als das Verhältnis -> Höhe anpassen
{
rect.Width = (int)Math.Round(rect.Height * _currentAspectRatio); // Zu breit -> Breite reduzieren, Math.Round für präzisere Ergebnisse
if (handle == DragHandle.TopLeft || handle == DragHandle.BottomLeft || handle == DragHandle.Left)
{
rect.X = right - rect.Width;
}
}
else
{
rect.Height = (int)Math.Round(rect.Width / _currentAspectRatio);
if (handle == DragHandle.TopLeft || handle == DragHandle.TopRight || handle == DragHandle.Top)
{
rect.Y = bottom - rect.Height;
}
}
rect.X = Math.Max(0, rect.X); // Innerhalb der PictureBox halten
rect.Y = Math.Max(0, rect.Y); // Innerhalb der PictureBox halten
if (rect.Right > pictureBox.Width) { rect.Width = pictureBox.Width - rect.X; }
if (rect.Bottom > pictureBox.Height) { rect.Height = pictureBox.Height - rect.Y; }
}
private Rectangle GetImageRectangle()
{
if (pictureBox.Image is null) { return Rectangle.Empty; }
var imgSize = pictureBox.Image.Size;
var ctrlSize = pictureBox.ClientSize; // Wichtig: ClientSize wegen Fixed3D-Rahmen
var ratioImg = (float)imgSize.Width / imgSize.Height;
var ratioCtrl = (float)ctrlSize.Width / ctrlSize.Height;
var x = 0;
var y = 0;
var w = ctrlSize.Width;
var h = ctrlSize.Height;
if (ratioImg > ratioCtrl) // Bild ist breiter als Box (Balken oben/unten)
{
h = (int)(w / ratioImg);
y = (ctrlSize.Height - h) / 2;
}
else // Bild ist höher als Box (Balken links/rechts)
{
w = (int)(h * ratioImg);
x = (ctrlSize.Width - w) / 2;
}
return new Rectangle(x, y, w, h);
}
private void PictureBox_MouseDown(object? sender, MouseEventArgs e)
{
if (pictureBox.Image is null || e.Button != MouseButtons.Left) { return; }
pictureBox.Focus(); // Erzwingt, dass ActiveControl = pictureBox wird; ist standardmäßig kein fokussierbares Steuerelement
var validRect = GetImageRectangle(); // Gültiger Bereich des Bildes in der PictureBox
var clampedPoint = new Point(Math.Clamp(e.X, validRect.Left, validRect.Right), Math.Clamp(e.Y, validRect.Top, validRect.Bottom));
_mouseDownPoint = clampedPoint; // Klickpunkt liegt jetzt innerhalb des Bildbereichs, auch wenn Original-Mausposition außerhalb war
_currentDragHandle = HitTest(e.Location);
if (_currentDragHandle != DragHandle.None)
{
_isDragging = true;
_dragStartPoint = e.Location; // Hier Original-Location lassen für flüssiges Delta
_isNewSelection = false;
}
else
{
_selectionRect = Rectangle.Empty;
_isNewSelection = true;
_isDragging = false;
pictureBox.Invalidate();
}
}
private void PictureBox_MouseMove(object? sender, MouseEventArgs e)
{
if (pictureBox.Image is null) { return; }
var validRect = GetImageRectangle();
// 1. Start des Ziehvorgangs erkennen
if (!_isDragging && _isNewSelection && e.Button == MouseButtons.Left)
{
// Prüfen, ob die Maus weit genug bewegt wurde (Schwellenwert)
if (Math.Abs(e.X - _mouseDownPoint.X) > SystemInformation.DragSize.Width || Math.Abs(e.Y - _mouseDownPoint.Y) > SystemInformation.DragSize.Height)
{
_isDragging = true;
_dragStartPoint = _mouseDownPoint;
}
}
if (!_isDragging)
{
SetCursor(HitTest(e.Location));
return;
}
// Mausposition auf den gültigen Bildbereich beschränken
var x = Math.Clamp(e.X, validRect.Left, validRect.Right);
var y = Math.Clamp(e.Y, validRect.Top, validRect.Bottom);
Rectangle newRect;
if (_isNewSelection)
{
// Rechteck zwischen Startpunkt und aktueller Mausposition
var x1 = Math.Min(_mouseDownPoint.X, x);
var y1 = Math.Min(_mouseDownPoint.Y, y);
var w = Math.Abs(_mouseDownPoint.X - x);
var h = Math.Abs(_mouseDownPoint.Y - y);
newRect = new Rectangle(x1, y1, w, h);
// Ratio berücksichtigen (falls aktiv)
if (_currentAspectRatio > 0)
{
// Wir müssen ermitteln, in welche Richtung gezogen wird, um den "Ankerpunkt" für die Ratio-Korrektur korrekt zu setzen.
DragHandle virtualHandle;
if (x < _mouseDownPoint.X && y < _mouseDownPoint.Y) { virtualHandle = DragHandle.TopLeft; }
else if (x >= _mouseDownPoint.X && y < _mouseDownPoint.Y) { virtualHandle = DragHandle.TopRight; }
else if (x < _mouseDownPoint.X && y >= _mouseDownPoint.Y) { virtualHandle = DragHandle.BottomLeft; }
else { virtualHandle = DragHandle.BottomRight; }
ApplyAspectRatio(ref newRect, virtualHandle);
}
}
else
{
// Logik für das Verschieben der Griffe
newRect = _selectionRect;
switch (_currentDragHandle)
{
case DragHandle.TopLeft:
newRect.X = x; newRect.Y = y;
newRect.Width = _selectionRect.Right - x;
newRect.Height = _selectionRect.Bottom - y;
break;
case DragHandle.TopRight:
newRect.Y = y;
newRect.Width = x - _selectionRect.X;
newRect.Height = _selectionRect.Bottom - y;
break;
case DragHandle.BottomLeft:
newRect.X = x;
newRect.Width = _selectionRect.Right - x;
newRect.Height = y - _selectionRect.Y;
break;
case DragHandle.BottomRight:
newRect.Width = x - _selectionRect.X;
newRect.Height = y - _selectionRect.Y;
break;
case DragHandle.Top:
newRect.Y = y; newRect.Height = _selectionRect.Bottom - y; break;
case DragHandle.Bottom:
newRect.Height = y - _selectionRect.Y; break;
case DragHandle.Left:
newRect.X = x; newRect.Width = _selectionRect.Right - x; break;
case DragHandle.Right:
newRect.Width = x - _selectionRect.X; break;
case DragHandle.Inside:
var dx = e.X - _dragStartPoint.X;
var dy = e.Y - _dragStartPoint.Y;
newRect.Offset(dx, dy);
// Begrenzung, damit man den Rahmen nicht aus dem Bild schieben kann
if (newRect.Left < validRect.Left) { newRect.X = validRect.Left; }
if (newRect.Top < validRect.Top) { newRect.Y = validRect.Top; }
if (newRect.Right > validRect.Right) { newRect.X = validRect.Right - newRect.Width; }
if (newRect.Bottom > validRect.Bottom) { newRect.Y = validRect.Bottom - newRect.Height; }
_dragStartPoint = e.Location;
break;
}
// Ratio bei bestehenden Griffen anwenden
if (_currentAspectRatio > 0 && _currentDragHandle != DragHandle.Inside) { ApplyAspectRatio(ref newRect, _currentDragHandle); }
}
// Abschließende Validierung
newRect = Utils.NormalizeRectangle(newRect); // Negative Breiten/Höhen korrigieren
newRect.Intersect(validRect); // Sicherstellen, dass alles im Bild bleibt
if (newRect != _selectionRect)
{
_selectionRect = newRect;
pictureBox.Invalidate();
}
}
private void PictureBox_MouseUp(object? sender, MouseEventArgs e)
{
_isDragging = false;
_isNewSelection = false;
_currentDragHandle = DragHandle.None;
pictureBox.Cursor = Cursors.Default;
clipContextMenuItem.Enabled = cropContextMenuItem.Enabled = cancelContextMenuItem.Enabled = cropToolStripMenuItem.Enabled = _selectionRect.Width > 0 && _selectionRect.Height > 0;
pictureBox.Invalidate();
}
private void PictureBox_Paint(object? sender, PaintEventArgs e)
{
if (_isLoading)
{
var text = "Bitte warten…";
var scaledFontSize = 24f * DeviceDpi / 96f;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
using var font = new Font("Segoe UI", scaledFontSize);
var textSize = e.Graphics.MeasureString(text, font);
var x = (pictureBox.ClientSize.Width - textSize.Width) / 2;
var y = (pictureBox.ClientSize.Height - textSize.Height) / 2;
e.Graphics.DrawString(text, font, Brushes.White, x, y);
}
else if (pictureBox.Image is null || _selectionRect.IsEmpty)
{
var shortcuts = new List<string>();
if (_currentAspectRatio > 0) { shortcuts.Add("Strg+0: frei"); }
if (Math.Abs(_currentAspectRatio - 1.0f) >= 0.01) { shortcuts.Add(shortcuts.Count == 0 ? "Strg+1: 1:1" : "-1: 1:1"); }
if (Math.Abs(_currentAspectRatio - (2f / 3f)) >= 0.01) { shortcuts.Add(shortcuts.Count == 0 ? "Strg+2: 2:3" : "-2: 2:3"); }
if (Math.Abs(_currentAspectRatio - (3f / 4f)) >= 0.01) { shortcuts.Add(shortcuts.Count == 0 ? "Strg+3: 3:4" : "-3: 3:4"); }
toolStripStatusSize.Text = $"{GetAspectRatioText()} ({string.Join(", ", shortcuts)})";
}
else
{
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.None;
var w = pictureBox.ClientSize.Width;
var h = pictureBox.ClientSize.Height;
using var shadowBrush = new SolidBrush(Color.FromArgb(120, Color.Black));
g.FillRectangle(shadowBrush, 0, 0, w, _selectionRect.Y); // Oben
g.FillRectangle(shadowBrush, 0, _selectionRect.Bottom, w, h - _selectionRect.Bottom); // Unten
g.FillRectangle(shadowBrush, 0, _selectionRect.Y, _selectionRect.X, _selectionRect.Height); // Links
g.FillRectangle(shadowBrush, _selectionRect.Right, _selectionRect.Y, w - _selectionRect.Right, _selectionRect.Height); // Rechts
var drawRect = new Rectangle(_selectionRect.X, _selectionRect.Y, _selectionRect.Width - 1, _selectionRect.Height - 1);
using var whitePen = new Pen(Color.White, 1);
g.DrawRectangle(whitePen, drawRect);
using var antPen = new Pen(Color.Black, 1);
antPen.DashStyle = DashStyle.Dash;
g.DrawRectangle(antPen, drawRect);
g.SmoothingMode = SmoothingMode.AntiAlias;
DrawHandle(e.Graphics, DragHandle.TopLeft);
DrawHandle(e.Graphics, DragHandle.TopRight);
DrawHandle(e.Graphics, DragHandle.BottomLeft);
DrawHandle(e.Graphics, DragHandle.BottomRight);
if (_currentAspectRatio <= 0)
{
DrawHandle(e.Graphics, DragHandle.Top);
DrawHandle(e.Graphics, DragHandle.Bottom);
DrawHandle(e.Graphics, DragHandle.Left);
DrawHandle(e.Graphics, DragHandle.Right);
}
var realRect = Utils.TranslateSelectionToImageCoordinates(_selectionRect, pictureBox);
var targetWidth = realRect.Width;
var targetHeight = realRect.Height;
var isOriginal = _downShift || targetWidth <= _settings.TargetWidth;
if (!isOriginal) // if (targetWidth > _settings.TargetWidth)
{
var ratio = (float)realRect.Height / realRect.Width;
targetWidth = _settings.TargetWidth;
targetHeight = (int)(targetWidth * ratio);
}
double zoomFactor = 0;
if (pictureBox.Image.Width > 0 && pictureBox.Image.Height > 0)
{
var widthRatio = (double)pictureBox.ClientSize.Width / pictureBox.Image.Width;
var heightRatio = (double)pictureBox.ClientSize.Height / pictureBox.Image.Height;
zoomFactor = Math.Min(widthRatio, heightRatio);
if (Math.Abs(zoomFactor - 1.0) < 0.011) { zoomFactor = 1.0; } // Snap-to-1, kleine Abweichungen ignorieren
}
var isZoom100 = zoomFactor == 1.0;
var monitorText = isZoom100 ? "" : $" Monitor {_selectionRect.Width}×{_selectionRect.Height},";
var ratioDisplay = GetAspectRatioText();
var compactText = $"{targetWidth}×{targetHeight} | {zoomFactor:0%} | {ratioDisplay}";
toolStripStatusSize.Text = compactText;
//}
}
}
private void DrawHandle(Graphics g, DragHandle handle)
{
var r = GetHandleRect(handle);
var shadow = r;
var offset = Math.Max(1, _handleSize / 8); // Schatten-Offset an DPI anpassen (ca. 10% der Handle-Größe oder berechnet)
shadow.Offset(offset, offset);
using var shadowBrush = new SolidBrush(Color.FromArgb(50, Color.Black));
g.FillRectangle(shadowBrush, shadow);
g.FillRectangle(Brushes.White, r);
var penWidth = _handleSize > 15 ? 2 : 1; // Die Umrandung bei hohen Auflösungen evtl. 2 Pixel dick machen
using var p = new Pen(Color.DarkSlateGray, penWidth);
g.DrawRectangle(p, r.X, r.Y, r.Width, r.Height);
}
private DragHandle HitTest(Point mouseLoc)
{
if (_selectionRect.IsEmpty) { return DragHandle.None; }
var tolerance = _handleSize / 4; // 25% der Griffgröße als Toleranz
foreach (var h in Enum.GetValues<DragHandle>())
{
if (h == DragHandle.None || h == DragHandle.Inside) { continue; }
var r = GetHandleRect(h);
r.Inflate(tolerance, tolerance); // Vergrößert nur die Prüf-Zone, nicht das Zeichnen
if (r.Contains(mouseLoc)) { return h; }
}
if (_selectionRect.Contains(mouseLoc)) { return DragHandle.Inside; }
return DragHandle.None;
}
private Rectangle GetHandleRect(DragHandle handle)
{
var r = _selectionRect;
var hs2 = _handleSize / 2;
return handle switch
{
DragHandle.TopLeft => new Rectangle(r.X - hs2, r.Y - hs2, _handleSize, _handleSize),
DragHandle.TopRight => new Rectangle(r.Right - hs2, r.Y - hs2, _handleSize, _handleSize),
DragHandle.BottomLeft => new Rectangle(r.X - hs2, r.Bottom - hs2, _handleSize, _handleSize),
DragHandle.BottomRight => new Rectangle(r.Right - hs2, r.Bottom - hs2, _handleSize, _handleSize),
DragHandle.Top => new Rectangle(r.X + r.Width / 2 - hs2, r.Y - hs2, _handleSize, _handleSize),
DragHandle.Bottom => new Rectangle(r.X + r.Width / 2 - hs2, r.Bottom - hs2, _handleSize, _handleSize),
DragHandle.Left => new Rectangle(r.X - hs2, r.Y + r.Height / 2 - hs2, _handleSize, _handleSize),
DragHandle.Right => new Rectangle(r.Right - hs2, r.Y + r.Height / 2 - hs2, _handleSize, _handleSize),
_ => Rectangle.Empty,
};
}
private void SetCursor(DragHandle handle)
{
pictureBox.Cursor = handle switch
{
DragHandle.TopLeft or DragHandle.BottomRight => Cursors.SizeNWSE,
DragHandle.TopRight or DragHandle.BottomLeft => Cursors.SizeNESW,
DragHandle.Top or DragHandle.Bottom => Cursors.SizeNS,
DragHandle.Left or DragHandle.Right => Cursors.SizeWE,
DragHandle.Inside => Cursors.SizeAll,
_ => Cursors.Default,
};
}
private void CancelSelection()
{
if (!_selectionRect.IsEmpty)
{
_selectionRect = Rectangle.Empty;
_isDragging = false;
_isNewSelection = false;
clipContextMenuItem.Enabled = cropContextMenuItem.Enabled = cancelContextMenuItem.Enabled = cropToolStripMenuItem.Enabled = false;
pictureBox.Invalidate();
}
}
private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
{
var ofd = new OpenFileDialog
{
Filter = "Bilddateien|*.jpg;*.jpeg;*.heic;*.avif;*.webp;*.png;*.bmp;*.gif;*.svg|" +
"JPEG-Dateien (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"SVG-Vektorgrafiken (*.svg)|*.svg|" +
"HEIC-Fotos (*.heic)|*.heic|" +
"PNG-Dateien (*.png)|*.png|" +
"AVIF-Dateien (*.avif)|*.avif|" +
"WebP-Bilder (*.webp)|*.webp|" +
"Alle Dateien (*.*)|*.*"
};
if (!string.IsNullOrEmpty(_settings.LastDirectory) && Directory.Exists(_settings.LastDirectory))
{
ofd.InitialDirectory = _settings.LastDirectory;
}
if (ofd.ShowDialog() == DialogResult.OK)
{
_settings.LastDirectory = Path.GetDirectoryName(ofd.FileName) ?? string.Empty;
SaveSettings(); // Den Pfad sofort in der XML-Datei sichern
LoadImageFile(ofd.FileName);
pictureBox.Focus();
}
}
private void CopySelectionToClipboard()
{
if (pictureBox.Image is null || _selectionRect.Width <= 1 || _selectionRect.Height <= 1)
{
Utils.MsgTaskDlg(Handle, "Keine Auswahl", "Bitte wählen Sie zuerst einen Bereich aus.", TaskDialogIcon.Warning);
return;
}
try
{
var sourceRect = Utils.TranslateSelectionToImageCoordinates(_selectionRect, pictureBox);
var originalImage = (Bitmap)pictureBox.Image;
using var croppedImage = new Bitmap(sourceRect.Width, sourceRect.Height);
using var g = Graphics.FromImage(croppedImage);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(originalImage, new Rectangle(0, 0, croppedImage.Width, croppedImage.Height), sourceRect, GraphicsUnit.Pixel);
Clipboard.SetImage(croppedImage);
toolStripStatusSize.Text = "Auswahl in die Zwischenablage kopiert.";
}
catch (Exception ex) { Utils.ErrTaskDlg(Handle, ex); }
}
private void CropToolStripMenuItem_Click(object sender, EventArgs e)
{
if (pictureBox.Image is null || _selectionRect.Width <= 1 || _selectionRect.Height <= 1)
{
Utils.MsgTaskDlg(Handle, "Keine Auswahl", "Bitte wählen Sie zuerst einen Bereich aus.", TaskDialogIcon.Warning);
return;
}
try
{
var sourceRect = Utils.TranslateSelectionToImageCoordinates(_selectionRect, pictureBox);
var originalImage = (Bitmap)pictureBox.Image;
if (sourceRect.Width <= 0 || sourceRect.Height <= 0) { throw new Exception("Auswahl ist ungültig."); }
var targetWidth = sourceRect.Width; // Zielgröße berechnen (Skalierung auf max 320px Breite)
var targetHeight = sourceRect.Height;
var isScaling = false;
if (!_downShift && targetWidth > _settings.TargetWidth)
{
var ratio = (float)sourceRect.Height / sourceRect.Width;
targetWidth = _settings.TargetWidth;
targetHeight = (int)(targetWidth * ratio);
isScaling = true;
}
var croppedImage = new Bitmap(targetWidth, targetHeight);
croppedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
using (var g = Graphics.FromImage(croppedImage))
{
if (isScaling)
{
// Hohe Qualität beim Verkleinern
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
}
else
{
// Pixel-perfekte Kopie beim reinen Ausschneiden (verhindert Weichzeichnen)
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.SmoothingMode = SmoothingMode.None;
g.PixelOffsetMode = PixelOffsetMode.None;
}
g.DrawImage(originalImage, new Rectangle(0, 0, targetWidth, targetHeight), sourceRect, GraphicsUnit.Pixel); // Quelle -> Ziel (0, 0, targetWidth, targetHeight)
}
Utils.TransferMetadata(originalImage, croppedImage); // Farbprofil von der Quelle auf das Ziel übertragen
var savePath = Path.Combine(_settings.SaveDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.Desktop), _settings.SaveImageName + ".jpg");
var jpgEncoder = Utils.GetEncoder(ImageFormat.Jpeg);
if (jpgEncoder is null) { croppedImage.Save(savePath, ImageFormat.Jpeg); }
else
{
using var myEncoderParameters = new EncoderParameters(1);
myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, _settings.JpegQuality);
croppedImage.Save(savePath, jpgEncoder, myEncoderParameters);
}
var savedToClipboard = true;
try { Clipboard.SetDataObject(savePath, true, 5, 10); }
catch (Exception) { savedToClipboard = false; }
var oldImage = pictureBox.Image;
pictureBox.Image = croppedImage;
pictureBox.SizeMode = PictureBoxSizeMode.CenterImage;
oldImage.Dispose();
_selectionRect = Rectangle.Empty;
pictureBox.Invalidate();
Text = _appName;
standardToolStripMenuItem.Enabled = cropToolStripMenuItem.Enabled = false;
var buffer = new char[32];
Utils.StrFormatByteSize(new FileInfo(savePath).Length, buffer, buffer.Length);
var nullIndex = Array.IndexOf(buffer, '\0');
var formattedSize = new string(buffer, 0, nullIndex >= 0 ? nullIndex : buffer.Length);
var allowDelete = _currentImagePath is not null && !Utils.IsLikelyMtpTempFile(_currentImagePath);
var btnClose = TaskDialogButton.Close;
var page = new TaskDialogPage
{
Caption = _appName,
Heading = $"{_settings.SaveImageName} gespeichert",
Text = $"<a href=\"{_settings.SaveDirectory}\">{savePath}</a> ({formattedSize})" + (savedToClipboard ? "\n\nDer Pfad wurde in die Zwischenablage kopiert." : ""),
Icon = TaskDialogIcon.ShieldSuccessGreenBar,
EnableLinks = true,
AllowCancel = true,
SizeToContent = true
};
TaskDialogCommandLinkButton? btnDeleteOriginal = null;
if (_settings.AllowDeleteOriginal && allowDelete)
{
btnDeleteOriginal = new TaskDialogCommandLinkButton("Originalbild löschen", "Die Datei in den Papierkorb verschieben");
page.Buttons.Add(btnDeleteOriginal);
}
page.Buttons.Add(btnClose);
page.Created += (s, e) =>
{
var hwnd = Utils.GetActiveWindow(); // Handle des TaskDialog
if (hwnd != IntPtr.Zero) // aktuelle Position minus ein Viertel der Form-Höhe
{
if (Utils.GetWindowRect(hwnd, out var rect)) { Utils.MoveWindow(hwnd, rect.Left, rect.Top - (Height / 4), rect.Right - rect.Left, rect.Bottom - rect.Top, true); }
}
};
page.LinkClicked += (s, args) =>
{
try
{
var dopusrt = @"C:\Program Files\GPSoftware\Directory Opus\dopusrt.exe";
using var process = new Process();
process.StartInfo.UseShellExecute = false;
if (File.Exists(dopusrt))
{
process.StartInfo.FileName = dopusrt;
process.StartInfo.Arguments = $"/cmd Go \"{savePath}\"";
process.Start();
}
else
{
process.StartInfo.FileName = "explorer.exe";
process.StartInfo.UseShellExecute = true;
process.StartInfo.Arguments = $"/select,\"{savePath}\"";
process.Start();
}
}
catch (Exception ex) { Utils.ErrTaskDlg(Handle, ex); }
};
var clickedButton = TaskDialog.ShowDialog(this, page);
if (clickedButton == btnDeleteOriginal && _currentImagePath is not null && File.Exists(_currentImagePath)) { DeleteLocalFile(_currentImagePath); }
if (clickedButton == btnClose || clickedButton == btnDeleteOriginal)
{
if (_settings.CloseAfterCropSuccess)
{
Close(); // pictureBox-Disposing erfolgt im FormClosed-Event
return;
}
}
pictureBox.Image?.Dispose();
pictureBox.Image = null;
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
_currentImagePath = null;
CancelSelection();
}
catch (Exception ex) { Utils.ErrTaskDlg(Handle, ex); }
}
private void DeleteLocalFile(string path)
{
try { FileSystem.DeleteFile(path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); }
catch (Exception ex) { Utils.ErrTaskDlg(Handle, ex); }
}
private void Main_Load(object sender, EventArgs e)
{
if (_currentImagePath is null && Clipboard.ContainsImage())
{
var clipboardImage = Clipboard.GetImage();
if (clipboardImage is not null && pictureBox.Image is null)
{
AdjustFormSizeToImage(clipboardImage);
pictureBox.Image = clipboardImage;
}
}
}
private void AdjustFormSizeToImage(Image image)
{
if (image is null) { return; }
var currentScreen = Screen.FromControl(this); // Bildschirm ermitteln, auf dem sich die Form aktuell befindet (Wichtig für Multi-Monitor!)
var workingArea = currentScreen.WorkingArea;
var originalWidth = image.Width;
var originalHeight = image.Height;
var horizontalChrome = Width - pictureBox.Width; // Differenz zwischen Form-Breite und PictureBox-Breite
var verticalChrome = Height - pictureBox.Height;
var maxImageWidth = workingArea.Width - horizontalChrome; // Verfügbarer Platz für das Bild
var maxImageHeight = workingArea.Height - verticalChrome;
var targetImageWidth = originalWidth; // Skalierte Bildgröße (initial unverändert)
var targetImageHeight = originalHeight;
var scaleX = (float)maxImageWidth / originalWidth; // Skalierungsfaktor (Verhältnis von Max-Platz zu Bildgröße)
var scaleY = (float)maxImageHeight / originalHeight;
if (scaleX < 1.0f || scaleY < 1.0f) // Bild ist zu groß für den verfügbaren Platz
{
var scaleFactor = Math.Min(scaleX, scaleY); // Den kleineren Skalierungsfaktor verwenden, um in beide Dimensionen zu passen
targetImageWidth = (int)(originalWidth * scaleFactor);
targetImageHeight = (int)(originalHeight * scaleFactor);
}
Width = targetImageWidth + horizontalChrome; // Neue Form-Größe setzen
Height = targetImageHeight + verticalChrome;
var newX = workingArea.Left + (workingArea.Width - Width) / 2; // Form zentrieren
var newY = workingArea.Top + (workingArea.Height - Height) / 2;
Location = new Point(newX, newY); // Position anwenden
}
private void Main_DragDrop(object sender, DragEventArgs e)
{
var files = (string[])e.Data!.GetData(DataFormats.FileDrop)!;
if (files.Length > 0) { LoadImageFile(files[0]); }
}
private void Main_DragEnter(object sender, DragEventArgs e)
{
if (e.Data!.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; }
}
private void HelpToolStripMenuItem_Click(object sender, EventArgs e) => ShowAboutDialog();
private void ShowAboutDialog()
{
var myVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.1";
var buildDate = Utils.GetBuildDate();
var page = new TaskDialogPage
{
Caption = "Über ImageCropper",
Heading = $"ImageCropper v{myVersion} ({buildDate:d})",
Text = $"© 2026 Dr. W. Happe. Alle Rechte vorbehalten.\nWebseite/Aktualisierung: <a href=\"https://www.netradio.info/misc/#imagecropper\">www.netradio.de</a>",
EnableLinks = true,
Icon = new TaskDialogIcon(Properties.Resources.icon32),
AllowCancel = true
};
var btnCustom = new TaskDialogCommandLinkButton($"{Path.GetFileName(_helpFilePath)} öffnen");
var btnClose = TaskDialogButton.Close;
page.Buttons.Add(btnClose);
page.Buttons.Add(btnCustom);
page.LinkClicked += (s, args) =>
{
try
{
Process.Start(new ProcessStartInfo { FileName = args.LinkHref, UseShellExecute = true });
}
catch (Exception ex) { Utils.ErrTaskDlg(page.BoundDialog?.Handle ?? IntPtr.Zero, ex); }
};
var result = TaskDialog.ShowDialog(this, page);
if (result == btnCustom) { Utils.StartFile(Handle, _helpFilePath); }
}
private void OpenSettings()
{
var tempSettings = _settings.Clone(); // Wir klonen die Settings, damit "Abbrechen" im Dialog Änderungen verwirft
using var dlg = new Opts(tempSettings);
if (dlg.ShowDialog(this) == DialogResult.OK)
{
_settings = tempSettings; // Einfach Referenz tauschen oder Werte kopieren
SaveSettings();
SetAspectRatio(_settings.DefaultAspectRatio);
UpdateEditorToolTip();
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Control | Keys.Tab:
CycleAspectRatio();
return true;
case Keys.Shift | Keys.Enter:
case Keys.Enter: // KeyDown-Event setzt explizit PictureBox als ActiveControl - ist eigentlich kein fokussierbares Control
if (!_selectionRect.IsEmpty && ActiveControl == pictureBox)
{
CropToolStripMenuItem_Click(this, EventArgs.Empty);
}
else if (_selectionRect.IsEmpty && pictureBox.Image is not null && (ActiveControl == pictureBox || ActiveControl is null))
{
StandardToolStripMenuItem_Click(this, EventArgs.Empty);
}
else if (pictureBox.Image is null && (ActiveControl == pictureBox || ActiveControl is null))
{
OpenToolStripMenuItem_Click(this, EventArgs.Empty);
}
return true;
case Keys.F1:
ShowAboutDialog();
return true;
case Keys.Escape:
if (_selectionRect.IsEmpty)
{
if (_settings.EscToExit) { Close(); }
}
else { CancelSelection(); }
return true;
case Keys.Control | Keys.N:
OpenToolStripMenuItem_Click(this, EventArgs.Empty);
return true;
case Keys.Control | Keys.S:
CropToolStripMenuItem_Click(this, EventArgs.Empty);
return true;
case Keys.Control | Keys.NumPad1:
case Keys.Control | Keys.D1:
SetAspectRatio(1.0f);
return true; // 1:1
case Keys.Control | Keys.NumPad2:
case Keys.Control | Keys.D2:
SetAspectRatio(2f / 3f);
return true; // 2:3
case Keys.Control | Keys.NumPad3:
case Keys.Control | Keys.D3:
SetAspectRatio(3f / 4f);
return true; // 3:4
case Keys.Control | Keys.NumPad0:
case Keys.Control | Keys.D0:
SetAspectRatio(0.0f);
return true; // Frei
case Keys.F2:
OpenSettings();
return true;
case Keys.F3:
OpenSettingsFile();
return true;
case Keys.Control | Keys.C:
CopySelectionToClipboard();
return true;
case Keys.Control | Keys.K:
if (!string.IsNullOrEmpty(_currentImagePath))
{
try { Clipboard.SetText(_currentImagePath); }
catch (Exception) { } // Fehler ignorieren bzw. leise abfangen
}
return true;
case Keys.Control | Keys.Delete:
if (!string.IsNullOrEmpty(_currentImagePath) && File.Exists(_currentImagePath))
{
var btnMoveToTrash = new TaskDialogButton("In den &Papierkorb verschieben");
var page = new TaskDialogPage
{
Caption = _appName,
Heading = "Originalbild löschen?",
Text = $"Die Datei wird in den Papierkorb verschoben:\n\n{_currentImagePath}",
Icon = new TaskDialogIcon(Properties.Resources.question32),
Buttons = { btnMoveToTrash, TaskDialogButton.Cancel },
DefaultButton = TaskDialogButton.Cancel // Sicherer Standard
};
if (TaskDialog.ShowDialog(this, page) == btnMoveToTrash)
{
pictureBox.Image?.Dispose(); // Bild in der PictureBox freigeben,
pictureBox.Image = null; // damit kein Dateizugriffsfehler auftritt
if (_currentImagePath is not null && File.Exists(_currentImagePath)) { DeleteLocalFile(_currentImagePath); }
Close(); // Programm beenden
}
}
return true;
}
if (_selectionRect != Rectangle.Empty)
{
var step = (keyData & Keys.Shift) == Keys.Shift ? 10 : 1; // Basis-Schrittweite (1px), mit Shift (10px)
var keyCode = keyData & Keys.KeyCode;
var isControl = (keyData & Keys.Control) == Keys.Control;
switch (keyCode)
{
case Keys.Left:
if (isControl) { _selectionRect.Width -= step; }
else { _selectionRect.X -= step; }
break;
case Keys.Right:
if (isControl) { _selectionRect.Width += step; }
else { _selectionRect.X += step; }
break;