-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
233 lines (197 loc) · 8.3 KB
/
MainWindow.xaml.cs
File metadata and controls
233 lines (197 loc) · 8.3 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
using Microsoft.Win32;
using SixLabors.ImageSharp;
using SharpImage = SixLabors.ImageSharp.Image;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace ImageConverter
{
public class ImageConversionJob : INotifyPropertyChanged
{
public string FilePath { get; set; }
public string FileName => Path.GetFileName(FilePath);
private string _targetFormat;
public string TargetFormat
{
get => _targetFormat;
set { _targetFormat = value; OnPropertyChanged(nameof(TargetFormat)); }
}
private string _status;
public string Status
{
get => _status;
set { _status = value; OnPropertyChanged(nameof(Status)); }
}
public List<string> SupportedFormats { get; } = new List<string> { "JPG", "PNG", "BMP", "GIF", "WEBP", "TIFF" };
public ImageConversionJob(string path)
{
FilePath = path;
Status = "Ожидание...";
string extension = Path.GetExtension(path).TrimStart('.').ToUpper();
if (SupportedFormats.Contains(extension))
{
TargetFormat = extension;
}
else
{
TargetFormat = "PNG";
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public partial class MainWindow : Window
{
private ObservableCollection<ImageConversionJob> _conversionJobs = new ObservableCollection<ImageConversionJob>();
public MainWindow()
{
InitializeComponent();
ImageListView.ItemsSource = _conversionJobs;
}
private void AddFilesButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Multiselect = true,
Title = "Выберите изображения для конвертации",
Filter = "Файлы изображений|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.webp;*.tiff|Все файлы|*.*"
};
if (openFileDialog.ShowDialog() == true)
{
foreach (var filePath in openFileDialog.FileNames)
{
_conversionJobs.Add(new ImageConversionJob(filePath));
}
}
}
private async void ConvertButton_Click(object sender, RoutedEventArgs e)
{
if (_conversionJobs.Count == 0) return;
var saveFolderDialog = new OpenFolderDialog
{
Title = "Выберите папку для сохранения конвертированных файлов"
};
if (saveFolderDialog.ShowDialog() != true) return;
string outputFolder = saveFolderDialog.FolderName;
SetUIEnabled(false);
ConversionProgressBar.Visibility = Visibility.Visible;
ConversionProgressBar.Value = 0;
var totalFiles = _conversionJobs.Count;
var processedFiles = 0;
await Task.Run(() =>
{
foreach (var job in _conversionJobs)
{
try
{
Dispatcher.Invoke(() => job.Status = "В процессе...");
using (SharpImage image = SharpImage.Load(job.FilePath))
{
string outputFileName = Path.ChangeExtension(job.FileName, "." + job.TargetFormat.ToLower());
string outputPath = Path.Combine(outputFolder, outputFileName);
image.Save(outputPath);
}
Dispatcher.Invoke(() => job.Status = "Успешно!");
}
catch (Exception ex)
{
Dispatcher.Invoke(() => job.Status = $"Ошибка: {ex.Message.Substring(0, Math.Min(30, ex.Message.Length))}");
}
processedFiles++;
Dispatcher.Invoke(() => ConversionProgressBar.Value = (double)processedFiles / totalFiles * 100);
}
});
StatusTextBlock.Text = $"Конвертация завершена. Файлов обработано: {processedFiles}.";
MessageBox.Show($"Конвертация завершена! Файлы сохранены в папке:\n{outputFolder}", "Готово", MessageBoxButton.OK, MessageBoxImage.Information);
SetUIEnabled(true);
ConversionProgressBar.Visibility = Visibility.Collapsed;
}
private void ClearListButton_Click(object sender, RoutedEventArgs e)
{
_conversionJobs.Clear();
}
private void SetAllButton_Click(object sender, RoutedEventArgs e)
{
if (_conversionJobs.Count == 0) return;
var dialog = new SetAllFormatDialog();
if (dialog.ShowDialog() == true)
{
string selectedFormat = dialog.SelectedFormat;
foreach (var job in _conversionJobs)
{
job.TargetFormat = selectedFormat;
}
}
}
private void ImageListView_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
e.Handled = true;
}
private void ImageListView_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
var imageExtensions = new[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp", ".tiff" };
foreach (var filePath in files)
{
if (imageExtensions.Contains(Path.GetExtension(filePath).ToLower()))
{
_conversionJobs.Add(new ImageConversionJob(filePath));
}
}
}
}
private void SetUIEnabled(bool isEnabled)
{
AddFilesButton.IsEnabled = isEnabled;
SetAllButton.IsEnabled = isEnabled;
ClearListButton.IsEnabled = isEnabled;
ConvertButton.IsEnabled = isEnabled;
ImageListView.IsEnabled = isEnabled;
}
}
public class SetAllFormatDialog : Window
{
public string SelectedFormat { get; private set; }
public SetAllFormatDialog()
{
Title = "Задать формат для всех";
Width = 300;
Height = 150;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
ResizeMode = ResizeMode.NoResize;
var stackPanel = new StackPanel { Margin = new Thickness(15) };
var label = new Label { Content = "Выберите целевой формат:" };
var comboBox = new ComboBox { ItemsSource = new List<string> { "JPG", "PNG", "BMP", "GIF", "WEBP", "TIFF" }, SelectedIndex = 0 };
var okButton = new Button { Content = "OK", IsDefault = true, Margin = new Thickness(0, 20, 0, 0) };
okButton.Click += (s, e) =>
{
SelectedFormat = comboBox.SelectedItem.ToString();
DialogResult = true;
};
stackPanel.Children.Add(label);
stackPanel.Children.Add(comboBox);
stackPanel.Children.Add(okButton);
Content = stackPanel;
}
}
}