BatchResizeView.axaml.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Documents;
  4. using Avalonia.Media;
  5. using Avalonia.Styling;
  6. using Avalonia.Threading;
  7. using ImageMagick;
  8. using PicView.Avalonia.FileSystem;
  9. using PicView.Avalonia.Navigation;
  10. using PicView.Avalonia.ViewModels;
  11. using PicView.Core.Extensions;
  12. using PicView.Core.FileHandling;
  13. using PicView.Core.ImageDecoding;
  14. using PicView.Core.Localization;
  15. using PicView.Core.Navigation;
  16. namespace PicView.Avalonia.Views;
  17. public partial class BatchResizeView : UserControl
  18. {
  19. private bool _isKeepingAspectRatio = true;
  20. private bool _isRunning;
  21. private CancellationTokenSource? _cancellationTokenSource;
  22. public BatchResizeView()
  23. {
  24. InitializeComponent();
  25. Loaded += delegate
  26. {
  27. if (DataContext is not MainViewModel vm)
  28. {
  29. return;
  30. }
  31. if (Settings.Theme.GlassTheme)
  32. {
  33. if (!Application.Current.TryGetResource("DisabledBackgroundColor",
  34. ThemeVariant.Dark, out var cc))
  35. {
  36. return;
  37. }
  38. if (cc is not Color bgColor)
  39. {
  40. return;
  41. }
  42. var background = new SolidColorBrush(bgColor);
  43. BatchLogBorder.Background = background;
  44. }
  45. SourceFolderTextBox.TextChanged += delegate { CheckIfValidDirectory(SourceFolderTextBox.Text); };
  46. SourceFolderTextBox.TextChanged += delegate
  47. {
  48. OutputFolderTextBox.Text = Path.Combine(SourceFolderTextBox.Text ?? string.Empty,
  49. TranslationHelper.Translation.BatchResize);
  50. };
  51. SourceFolderButton.Click += async delegate
  52. {
  53. var directory = await FilePicker.SelectDirectory();
  54. if (string.IsNullOrWhiteSpace(directory))
  55. {
  56. return;
  57. }
  58. SourceFolderTextBox.Text = directory;
  59. };
  60. OutputFolderButton.Click += async delegate
  61. {
  62. var directory = await FilePicker.SelectDirectory();
  63. if (string.IsNullOrWhiteSpace(directory))
  64. {
  65. return;
  66. }
  67. OutputFolderTextBox.Text = directory;
  68. };
  69. LinkChainButton.Click += delegate { ToggleAspectRatio(); };
  70. StartButton.Click += async (_, _) =>
  71. {
  72. try
  73. {
  74. await StartBatchResize();
  75. }
  76. catch (Exception e)
  77. {
  78. #if DEBUG
  79. Console.WriteLine(e);
  80. #endif
  81. }
  82. };
  83. CancelButton.Click += async delegate
  84. {
  85. if (_isRunning)
  86. {
  87. await CancelBatchResize();
  88. }
  89. else
  90. {
  91. Reset();
  92. }
  93. };
  94. if (!NavigationManager.CanNavigate(vm))
  95. {
  96. return;
  97. }
  98. SourceFolderTextBox.Text = vm.FileInfo?.DirectoryName ?? string.Empty;
  99. };
  100. }
  101. private void ToggleAspectRatio()
  102. {
  103. _isKeepingAspectRatio = !_isKeepingAspectRatio;
  104. LinkChainImage.IsVisible = _isKeepingAspectRatio;
  105. UnlinkChainImage.IsVisible = !_isKeepingAspectRatio;
  106. }
  107. private void Reset()
  108. {
  109. _isKeepingAspectRatio = true;
  110. LinkChainImage.IsVisible = true;
  111. UnlinkChainImage.IsVisible = false;
  112. ResetProgress();
  113. ConversionComboBox.SelectedIndex = 0;
  114. ConversionComboBox.SelectedItem = NoConversion;
  115. CompressionComboBox.SelectedIndex = 0;
  116. CompressionComboBox.SelectedItem = Lossless;
  117. IsQualityEnabledBox.IsChecked = false;
  118. QualitySlider.Value = 75;
  119. ResizeComboBox.SelectedIndex = 0;
  120. ResizeComboBox.SelectedItem = NoResizeBox;
  121. ThumbnailsComboBox.SelectedIndex = 0;
  122. ThumbnailsComboBox.SelectedItem = NoThumbnailsItem;
  123. BatchLogContainer.Children.Clear();
  124. if (DataContext is not MainViewModel vm)
  125. {
  126. return;
  127. }
  128. if (!NavigationManager.CanNavigate(vm))
  129. {
  130. return;
  131. }
  132. SourceFolderTextBox.Text = vm.FileInfo?.DirectoryName ?? string.Empty;
  133. }
  134. private void ResetProgress()
  135. {
  136. ProgressBar.Value = 0;
  137. _isRunning = false;
  138. StartButton.IsEnabled = true;
  139. CancelButtonTextBlock.Text = TranslationHelper.Translation.Reset;
  140. CancelButton.Classes.Remove("errorHover");
  141. CancelButton.Classes.Add("altHover");
  142. InputStackPanel.Opacity = 1;
  143. InputStackPanel.IsHitTestVisible = true;
  144. }
  145. private async Task CancelBatchResize()
  146. {
  147. await _cancellationTokenSource?.CancelAsync();
  148. CancelButtonTextBlock.Text = TranslationHelper.Translation.Reset;
  149. StartButton.IsEnabled = true;
  150. _isRunning = false;
  151. ProgressBar.Value = 0;
  152. }
  153. private async Task StartBatchResize()
  154. {
  155. try
  156. {
  157. _cancellationTokenSource = new CancellationTokenSource();
  158. CancelButtonTextBlock.Text = TranslationHelper.Translation.Cancel;
  159. CancelButton.Classes.Remove("altHover");
  160. CancelButton.Classes.Add("errorHover");
  161. StartButton.IsEnabled = false;
  162. InputStackPanel.Opacity = 0.5;
  163. InputStackPanel.IsHitTestVisible = false;
  164. _isRunning = true;
  165. var files = await Task.FromResult(
  166. FileListHelper.RetrieveFiles(new FileInfo(SourceFolderTextBox.Text)))
  167. .ConfigureAwait(true);
  168. if (!Directory.Exists(OutputFolderTextBox.Text))
  169. {
  170. Directory.CreateDirectory(OutputFolderTextBox.Text);
  171. }
  172. var outputFolder = string.IsNullOrWhiteSpace(OutputFolderTextBox.Text)
  173. ? SourceFolderTextBox.Text
  174. : OutputFolderTextBox.Text;
  175. var toConvert = !NoConversion.IsSelected;
  176. var pngSelected = PngItem.IsSelected;
  177. var jpgSelected = JpgItem.IsSelected;
  178. var webpSelected = WebpItem.IsSelected;
  179. var avifSelected = AvifItem.IsSelected;
  180. var heicSelected = HeicItem.IsSelected;
  181. var jxlSelected = JxlItem.IsSelected;
  182. var qualityEnabled = IsQualityEnabledBox.IsChecked.HasValue && IsQualityEnabledBox.IsChecked.Value;
  183. var qualityValue = (uint)QualitySlider.Value;
  184. var losslessCompress = Lossless.IsSelected;
  185. var lossyCompress = Lossy.IsSelected;
  186. Percentage? percentage = null;
  187. if (PercentageResizeBox.IsSelected)
  188. {
  189. if (int.TryParse(PercentageValueBox.Text, out var percentageValue))
  190. {
  191. percentage = new Percentage(percentageValue);
  192. }
  193. }
  194. uint width = 0, height = 0;
  195. if (WidthResizeBox.IsSelected)
  196. {
  197. if (uint.TryParse(WidthValueBox.Text, out var widthValue))
  198. {
  199. width = widthValue;
  200. }
  201. }
  202. else if (HeightResizeBox.IsSelected)
  203. {
  204. if (uint.TryParse(HeightValueBox.Text, out var heightValue))
  205. {
  206. height = heightValue;
  207. }
  208. }
  209. else if (WidthAndHeightResizeBox.IsSelected)
  210. {
  211. if (uint.TryParse(WidthAndHeightWidthValueBox.Text, out var widthValue))
  212. {
  213. width = widthValue;
  214. }
  215. if (uint.TryParse(WidthAndHeightHeightValueBox.Text, out var heightValue))
  216. {
  217. height = heightValue;
  218. }
  219. }
  220. var enumerable = files as string[] ?? files.ToArray();
  221. ProgressBar.Maximum = enumerable.Length;
  222. ProgressBar.Value = 0;
  223. var options = new ParallelOptions
  224. {
  225. CancellationToken = _cancellationTokenSource.Token,
  226. MaxDegreeOfParallelism = Environment.ProcessorCount - 1
  227. };
  228. await Parallel.ForEachAsync(enumerable, options, async (file, token) =>
  229. {
  230. token.ThrowIfCancellationRequested();
  231. var ext = Path.GetExtension(file);
  232. var destination = Path.Combine(outputFolder, Path.GetFileName(file));
  233. var fileInfo = new FileInfo(file);
  234. using var magick = new MagickImage();
  235. magick.Ping(file);
  236. var oldSize = $" ({magick.Width} x {magick.Height}{ImageTitleFormatter.FormatAspectRatio((int)magick.Width, (int)magick.Height)}{fileInfo.Length.GetReadableFileSize()}";
  237. if (toConvert)
  238. {
  239. string GetTargetExtension()
  240. {
  241. if (pngSelected) return ".png";
  242. if (jpgSelected) return ".jpg";
  243. if (webpSelected) return ".webp";
  244. if (avifSelected) return ".avif";
  245. if (heicSelected) return ".heic";
  246. if (jxlSelected) return ".jxl";
  247. return ext;
  248. }
  249. ext = GetTargetExtension();
  250. destination = Path.ChangeExtension(destination, ext);
  251. }
  252. uint? quality = null;
  253. if (qualityEnabled)
  254. {
  255. if (ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(destination)
  256. .Equals(".jpg", StringComparison.OrdinalIgnoreCase) ||
  257. Path.GetExtension(destination).Equals(".jpeg", StringComparison.OrdinalIgnoreCase) ||
  258. ext.Equals(".png", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(destination)
  259. .Equals(".png", StringComparison.OrdinalIgnoreCase))
  260. {
  261. quality = qualityValue;
  262. }
  263. }
  264. await using var stream = FileHelper.GetOptimizedFileStream(fileInfo, true);
  265. var success = await SaveImageFileHelper.SaveImageAsync(
  266. stream,
  267. null,
  268. destination,
  269. width,
  270. height,
  271. quality,
  272. ext,
  273. null,
  274. percentage,
  275. losslessCompress,
  276. lossyCompress,
  277. _isKeepingAspectRatio).ConfigureAwait(false);
  278. if (success)
  279. {
  280. using var newMagick = new MagickImage();
  281. newMagick.Ping(destination);
  282. var newFileInfo = new FileInfo(destination);
  283. var newSize = $" ({newMagick.Width} x {newMagick.Height}{ImageTitleFormatter.FormatAspectRatio((int)newMagick.Width, (int)newMagick.Height)}{newFileInfo.Length.GetReadableFileSize()}";
  284. await Dispatcher.UIThread.InvokeAsync(() =>
  285. {
  286. BatchLogContainer.Children.Add(CreateTextBlockLog(Path.GetFileName(file), oldSize,
  287. newSize));
  288. });
  289. await ProcessThumbs(file, Path.GetDirectoryName(destination), quality, ext).ConfigureAwait(false);
  290. await Dispatcher.UIThread.InvokeAsync(() =>
  291. {
  292. ProgressBar.Value++;
  293. });
  294. }
  295. }).ConfigureAwait(false);
  296. return;
  297. async Task ProcessThumbs(string? file, string? destinationDirectory, uint? quality, string? ext)
  298. {
  299. _cancellationTokenSource.Token.ThrowIfCancellationRequested();
  300. var toProcess = true;
  301. await Dispatcher.UIThread.InvokeAsync(() =>
  302. {
  303. if (ThumbnailsComboBox.SelectedIndex <= 0)
  304. {
  305. toProcess = false;
  306. }
  307. });
  308. if (!toProcess)
  309. {
  310. return;
  311. }
  312. var destination = string.Empty;
  313. for (var i = 1; i <= 7; i++)
  314. {
  315. bool thumbIsPercentageResized;
  316. bool thumbIsWidthResized;
  317. bool thumbIsHeightResized;
  318. uint thumbWidth = 0, thumbHeight = 0;
  319. Percentage? thumbPercentage = null;
  320. await Dispatcher.UIThread.InvokeAsync(() =>
  321. {
  322. // Dynamically construct the control names
  323. var percentageItemName = $"Thumb{i}PercentageItem";
  324. var widthItemName = $"Thumb{i}WidthItem";
  325. var heightItemName = $"Thumb{i}HeightItem";
  326. var valueBoxName = $"Thumb{i}ValueBox";
  327. var outputBoxName = $"Thumb{i}OutputBox";
  328. // Find controls based on their names
  329. var percentageItem = this.FindControl<ComboBoxItem>(percentageItemName);
  330. var widthItem = this.FindControl<ComboBoxItem>(widthItemName);
  331. var heightItem = this.FindControl<ComboBoxItem>(heightItemName);
  332. var valueBox = this.FindControl<TextBox>(valueBoxName);
  333. var outputBox = this.FindControl<TextBox>(outputBoxName);
  334. // Check which resizing option is selected
  335. thumbIsPercentageResized = percentageItem?.IsSelected ?? false;
  336. thumbIsWidthResized = widthItem?.IsSelected ?? false;
  337. thumbIsHeightResized = heightItem?.IsSelected ?? false;
  338. // Parse the value from the TextBox
  339. if (uint.TryParse(valueBox?.Text, out var thumbValue))
  340. {
  341. if (thumbIsPercentageResized)
  342. {
  343. thumbPercentage = new Percentage(thumbValue);
  344. }
  345. if (thumbIsWidthResized)
  346. {
  347. thumbWidth = thumbValue;
  348. }
  349. if (thumbIsHeightResized)
  350. {
  351. thumbHeight = thumbValue;
  352. }
  353. }
  354. if (!Directory.Exists(destinationDirectory))
  355. {
  356. Directory.CreateDirectory(destinationDirectory);
  357. }
  358. destination = Path.Combine(destinationDirectory, outputBox.Text, Path.GetFileName(file));
  359. if (!Directory.Exists(Path.GetDirectoryName(destination)))
  360. {
  361. Directory.CreateDirectory(Path.GetDirectoryName(destination));
  362. }
  363. });
  364. var fileInfo = new FileInfo(file);
  365. using var magick = new MagickImage();
  366. magick.Ping(file);
  367. var oldSize = $" ({magick.Width} x {magick.Height}{ImageTitleFormatter.FormatAspectRatio((int)magick.Width, (int)magick.Height)}{fileInfo.Length.GetReadableFileSize()}";
  368. await using var stream = FileHelper.GetOptimizedFileStream(fileInfo, true);
  369. _cancellationTokenSource.Token.ThrowIfCancellationRequested();
  370. var success = await SaveImageFileHelper.SaveImageAsync(stream,
  371. null,
  372. destination,
  373. thumbWidth,
  374. thumbHeight,
  375. quality,
  376. ext,
  377. null,
  378. thumbPercentage,
  379. losslessCompress,
  380. lossyCompress,
  381. _isKeepingAspectRatio).ConfigureAwait(false);
  382. if (success)
  383. {
  384. using var newMagick = new MagickImage();
  385. newMagick.Ping(destination);
  386. var newFileInfo = new FileInfo(destination);
  387. var newSize = $" ({newMagick.Width} x {newMagick.Height}{ImageTitleFormatter.FormatAspectRatio((int)newMagick.Width, (int)newMagick.Height)}{newFileInfo.Length.GetReadableFileSize()}";
  388. await Dispatcher.UIThread.InvokeAsync(() =>
  389. {
  390. _cancellationTokenSource.Token.ThrowIfCancellationRequested();
  391. BatchLogContainer.Children.Add(CreateTextBlockLog(Path.GetFileName(file), oldSize,
  392. newSize));
  393. });
  394. }
  395. }
  396. }
  397. }
  398. catch (Exception e)
  399. {
  400. #if DEBUG
  401. Console.WriteLine(e);
  402. #endif
  403. }
  404. finally
  405. {
  406. await Dispatcher.UIThread.InvokeAsync(ResetProgress);
  407. }
  408. }
  409. private void CheckIfValidDirectory(string path)
  410. {
  411. if (!Directory.Exists(path))
  412. {
  413. StartButton.IsEnabled = false;
  414. return;
  415. }
  416. StartButton.IsEnabled = true;
  417. }
  418. private TextBlock CreateTextBlockLog(string fileName, string oldSize, string newSize)
  419. {
  420. var textBlock = new TextBlock
  421. {
  422. Classes = { "txt", "txtShadow" },
  423. Padding = new Thickness(0, 0, 0, 5),
  424. MaxWidth = 580
  425. };
  426. var fileNameRun = new Run
  427. {
  428. Text = fileName
  429. };
  430. var oldSizeRun = new Run
  431. {
  432. Text = oldSize,
  433. Foreground = Brushes.Red,
  434. TextDecorations = TextDecorations.Strikethrough
  435. };
  436. var newSizeRun = new Run
  437. {
  438. Text = newSize,
  439. Foreground = Brushes.Green,
  440. FontFamily = new FontFamily("avares://PicView.Avalonia/Assets/Fonts/Roboto-Bold.ttf#Roboto")
  441. };
  442. textBlock.Inlines.Add(fileNameRun);
  443. textBlock.Inlines.Add(oldSizeRun);
  444. textBlock.Inlines.Add(newSizeRun);
  445. return textBlock;
  446. }
  447. ~BatchResizeView()
  448. {
  449. _cancellationTokenSource?.Cancel();
  450. _cancellationTokenSource?.Dispose();
  451. }
  452. }