Browse Source

#37 Add thumbnail generation support, work in progress

Ruben 4 năm trước cách đây
mục cha
commit
4ed437ba74

+ 92 - 0
PicView/ImageHandling/BatchFunctions.cs

@@ -0,0 +1,92 @@
+using ImageMagick;
+using PicView.FileHandling;
+using PicView.UILogic;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+using System.Windows.Threading;
+
+namespace PicView.ImageHandling
+{
+    internal static class BatchFunctions
+    {
+        internal static async Task RunAsync(List<string> sourceFileist, int resizeAmount, int quality,
+            Percentage? percentage, bool? compress, string outputFolder, bool toResize, TextBox LogTextBox,
+            ProgressBar progressBar) => await Task.Run(() =>
+        {
+            Parallel.For(0, sourceFileist.Count, async i =>
+            {
+                var sourceFile = new FileInfo(sourceFileist[i]);
+                var destination = outputFolder + sourceFile.Name;
+                var sb = new StringBuilder();
+
+                if (toResize)
+                {
+                    _ = doResize(LogTextBox, progressBar, sb, sourceFile, resizeAmount, quality, percentage, destination, compress).ConfigureAwait(false);
+                }
+                else if (compress.HasValue)
+                {
+                    if (sourceFile.DirectoryName == outputFolder)
+                    {
+                        await ImageFunctions.OptimizeImageAsync(sourceFile.FullName).ConfigureAwait(false);
+                        var destinationFile = new FileInfo(destination);
+                        sb.Append(sourceFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length))
+                            .Append(" 🠚 ").Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length)).AppendLine(Environment.NewLine);
+                    }
+                    else
+                    {
+
+                    }
+
+                    report(LogTextBox, progressBar, sb);
+                }
+            });
+        });
+
+        static async Task doResize(TextBox LogTextBox, ProgressBar progressBar, StringBuilder sb, FileInfo? sourceFile, int resizeAmount, int quality = 100, Percentage? percentage = null, string? destination = null, bool? compress = null)
+        {
+            var success = await ImageSizeFunctions.ResizeImageAsync(sourceFile.FullName, resizeAmount, resizeAmount, quality, percentage, destination, compress).ConfigureAwait(false);
+            if (success is false) { return; }
+
+            var destinationFile = new FileInfo(destination);
+            sb.Append(sourceFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length)).Append(" 🠚 ")
+                .Append(destinationFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(destinationFile.Length)).
+                Append(' ').AppendLine(Environment.NewLine);
+
+            report(LogTextBox, progressBar, sb);
+        }
+
+        static void report(TextBox LogTextBox, ProgressBar progressBar, StringBuilder sb)
+        {
+            ConfigureWindows.GetResizeWindow.Dispatcher.Invoke(DispatcherPriority.Render, () =>
+            {
+                LogTextBox.Text += sb.ToString();
+                progressBar.Value++;
+                LogTextBox.ScrollToEnd();
+
+                if (progressBar.Value == progressBar.Maximum)
+                {
+                    LogTextBox.Text += Environment.NewLine + "Completed";
+                }
+            });
+        }
+
+        internal class ThumbNailHolder
+        {
+            internal string directory;
+            internal int size;
+            internal Percentage? percentage;
+
+            internal ThumbNailHolder(string directory, int size, Percentage? percentage)
+            {
+                this.directory = directory;
+                this.size = size;
+                this.percentage = percentage;
+            }
+        }
+    }
+}

+ 7 - 11
PicView/ImageHandling/ImageSizeFunctions.cs

@@ -47,8 +47,6 @@ namespace PicView.ImageHandling
             if (File.Exists(file) == false) { return false; }
             if (File.Exists(file) == false) { return false; }
             if (width < 0 && percentage is not null || height < 0 && percentage is not null) { return false; }
             if (width < 0 && percentage is not null || height < 0 && percentage is not null) { return false; }
 
 
-            var filestream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, true);
-
             var magick = new MagickImage()
             var magick = new MagickImage()
             {
             {
                 ColorSpace = ColorSpace.Transparent
                 ColorSpace = ColorSpace.Transparent
@@ -61,7 +59,7 @@ namespace PicView.ImageHandling
 
 
             try
             try
             {
             {
-                await magick.ReadAsync(filestream).ConfigureAwait(false);
+                await magick.ReadAsync(file).ConfigureAwait(false);
             }
             }
             catch (MagickException e)
             catch (MagickException e)
             {
             {
@@ -84,21 +82,17 @@ namespace PicView.ImageHandling
 
 
                 if (destination is null)
                 if (destination is null)
                 {
                 {
-                    await magick.WriteAsync(filestream).ConfigureAwait(false);
-                    await filestream.DisposeAsync().ConfigureAwait(false);
+                    await magick.WriteAsync(file).ConfigureAwait(false);
                 }
                 }
                 else
                 else
                 {
                 {
-                    await filestream.DisposeAsync().ConfigureAwait(false);
                     var dir = Path.GetDirectoryName(destination);
                     var dir = Path.GetDirectoryName(destination);
                     if (dir is null) { return false; }
                     if (dir is null) { return false; }
                     if (Directory.Exists(dir) == false)
                     if (Directory.Exists(dir) == false)
                     {
                     {
                         Directory.CreateDirectory(dir);
                         Directory.CreateDirectory(dir);
                     }
                     }
-                    var destinationStream = new FileStream(destination, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true);
-                    await magick.WriteAsync(destinationStream).ConfigureAwait(false);
-                    await destinationStream.DisposeAsync().ConfigureAwait(false);
+                    await magick.WriteAsync(destination).ConfigureAwait(false);
                 }
                 }
             }
             }
             catch (MagickException e)
             catch (MagickException e)
@@ -118,11 +112,13 @@ namespace PicView.ImageHandling
                     OptimalCompression = compress.Value,
                     OptimalCompression = compress.Value,
                 };
                 };
 
 
-                if (imageOptimizer.IsSupported(file) == false)
+                var x = destination is null ? file : destination;
+
+                if (imageOptimizer.IsSupported(x) == false)
                 {
                 {
                     return true;
                     return true;
                 }
                 }
-                imageOptimizer.Compress(file);
+                imageOptimizer.Compress(x);
             }
             }
 
 
             return true;
             return true;

+ 2 - 2
PicView/Views/UserControls/Misc/ThumbnailOutputUC.xaml

@@ -35,8 +35,8 @@
             <StackPanel Orientation="Horizontal">
             <StackPanel Orientation="Horizontal">
 
 
                 <ComboBox Width="130">
                 <ComboBox Width="130">
-                    <ComboBoxItem Content="{StaticResource Width}" />
-                    <ComboBoxItem Content="{StaticResource Height}" />
+                    <ComboBoxItem x:Name="WidthBox" Content="{StaticResource Width}" />
+                    <ComboBoxItem x:Name="HeightBox" Content="{StaticResource Height}" />
                     <ComboBoxItem
                     <ComboBoxItem
                         Name="Percentage"
                         Name="Percentage"
                         Content="Percentage"
                         Content="Percentage"

+ 1 - 1
PicView/Views/Windows/ResizeWindow.xaml

@@ -302,7 +302,7 @@
                 AcceptsReturn="True"
                 AcceptsReturn="True"
                 BorderThickness="1.5"
                 BorderThickness="1.5"
                 Effect="{StaticResource MenuShadowButtonBorder}"
                 Effect="{StaticResource MenuShadowButtonBorder}"
-                MaxLines="999"
+                MaxLines="9999"
                 TextWrapping="Wrap"
                 TextWrapping="Wrap"
                 ToolTip="{x:Null}"
                 ToolTip="{x:Null}"
                 VerticalScrollBarVisibility="Visible" />
                 VerticalScrollBarVisibility="Visible" />

+ 37 - 65
PicView/Views/Windows/ResizeWindow.xaml.cs

@@ -1,4 +1,5 @@
-using PicView.Animations;
+using ImageMagick;
+using PicView.Animations;
 using PicView.ChangeImage;
 using PicView.ChangeImage;
 using PicView.FileHandling;
 using PicView.FileHandling;
 using PicView.ImageHandling;
 using PicView.ImageHandling;
@@ -21,6 +22,7 @@ namespace PicView.Views.Windows
     public partial class ResizeWindow : Window
     public partial class ResizeWindow : Window
     {
     {
         bool running;
         bool running;
+        System.Collections.Generic.List<BatchFunctions.ThumbNailHolder> thumbs = new();
         public ResizeWindow()
         public ResizeWindow()
         {
         {
             Title = Application.Current.Resources["BatchResize"] + " - PicView";
             Title = Application.Current.Resources["BatchResize"] + " - PicView";
@@ -146,8 +148,8 @@ namespace PicView.Views.Windows
                     running = true;
                     running = true;
 
 
                     bool toResize = NoResize.IsSelected == false;
                     bool toResize = NoResize.IsSelected == false;
-                    int ResizeAmount = 0;
-                    ImageMagick.Percentage? percentage = null;
+                    int resizeAmount = 0;
+                    Percentage? percentage = null;
                     int quality = 100;
                     int quality = 100;
                     bool? compress = null;
                     bool? compress = null;
                     if (LosslessCompressionChoice.IsSelected)
                     if (LosslessCompressionChoice.IsSelected)
@@ -168,17 +170,17 @@ namespace PicView.Views.Windows
                     {
                     {
                         if (PercentageResize.IsSelected && int.TryParse(PercentageBox.Text, out var number))
                         if (PercentageResize.IsSelected && int.TryParse(PercentageBox.Text, out var number))
                         {
                         {
-                            percentage = new ImageMagick.Percentage(number);
+                            percentage = new Percentage(number);
                         }
                         }
                         else
                         else
                         {
                         {
                             if (WidthResize.IsSelected && int.TryParse(WidthValue.Text, out var resizeWidth))
                             if (WidthResize.IsSelected && int.TryParse(WidthValue.Text, out var resizeWidth))
                             {
                             {
-                                ResizeAmount = resizeWidth;
+                                resizeAmount = resizeWidth;
                             }
                             }
                             else if (HeightResize.IsSelected && int.TryParse(HeightValue.Text, out var resizeHeight))
                             else if (HeightResize.IsSelected && int.TryParse(HeightValue.Text, out var resizeHeight))
                             {
                             {
-                                ResizeAmount = resizeHeight;
+                                resizeAmount = resizeHeight;
                             }
                             }
                         }
                         }
                     }
                     }
@@ -191,74 +193,44 @@ namespace PicView.Views.Windows
 
 
                     var sourceFileist = sameDir ? Navigation.Pics : FileLists.FileList(new FileInfo(SourceFolderInput.Text));
                     var sourceFileist = sameDir ? Navigation.Pics : FileLists.FileList(new FileInfo(SourceFolderInput.Text));
                     string outputFolder = OutputFolderInput.Text + @"\";
                     string outputFolder = OutputFolderInput.Text + @"\";
-                    ProgressBar.Maximum = sourceFileist.Count;
                     var cancelToken = new CancellationTokenSource();
                     var cancelToken = new CancellationTokenSource();
-                    int thumbs;
-                    var selectedThumb = (ComboBoxItem)ThumbnailsComboBox.SelectedItem;
-                    if (int.TryParse(selectedThumb.Content.ToString(), out var thumbNumber))
-                    {
-                        thumbs = thumbNumber;
-                    }
-                    else
-                    {
-                        thumbs = 0;
-                    }
+                    int thumbSize = 0;
+                    Percentage? thumbPercentage = null;
 
 
-                    await Task.Run(() =>
+                    for (int i = 0; i < GeneratedThumbnailsContainer.Children.Count; i++)
                     {
                     {
-                        Parallel.For(0, sourceFileist.Count, async i =>
+                        var container = (UserControls.ThumbnailOutputUC)GeneratedThumbnailsContainer.Children[i];
+                        if (container == null) { continue; }
+                        if (container.Percentage.IsSelected && int.TryParse(container.ValueBox.Text, out var number))
                         {
                         {
-                            var sourceFile = new FileInfo(sourceFileist[i]);
-                            var destination = outputFolder + sourceFile.Name;
-                            var destinationFile = new FileInfo(destination);
-                            var sb = new StringBuilder();
-
-                            if (toResize)
+                            thumbPercentage = new Percentage(number);
+                        }
+                        else
+                        {
+                            if (container.WidthBox.IsSelected && int.TryParse(WidthValue.Text, out var resizeWidth))
                             {
                             {
-                                var success = await ImageSizeFunctions.ResizeImageAsync(sourceFile.FullName, ResizeAmount, ResizeAmount, quality, percentage, destination, compress).ConfigureAwait(false);
-                                if (running is false)
-                                {
-                                    cancelToken.Cancel();
-                                }
-                                if (success)
-                                {
-                                    sb.Append(sourceFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length)).Append(" 🠚 ")
-                                        .Append(destinationFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(destinationFile.Length)).
-                                        Append(' ').AppendLine(Environment.NewLine);
-                                }
+                                thumbSize = resizeWidth;
                             }
                             }
-                            else if (thumbs <= 0 && compress.HasValue)
+                            else if (container.HeightBox.IsSelected && int.TryParse(HeightValue.Text, out var resizeHeight))
                             {
                             {
-                                if (sourceFile.DirectoryName == destinationFile.DirectoryName)
-                                {
-                                    sb.Append(sourceFile.DirectoryName).Append('/').Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length));
-                                    await ImageFunctions.OptimizeImageAsync(sourceFile.FullName).ConfigureAwait(false);
-                                    sb.Append(" 🠚 ").Append(sourceFile.Name).Append(' ').Append(FileFunctions.GetSizeReadable(sourceFile.Length)).AppendLine(Environment.NewLine);
-                                }
-                                else
-                                {
-
-                                }
-
-                                if (running is false)
-                                {
-                                    cancelToken.Cancel();
-                                }
+                                thumbSize = resizeHeight;
                             }
                             }
+                        }
+                        thumbs.Add(new BatchFunctions.ThumbNailHolder(container.OutPutStringBox.Text, thumbSize, thumbPercentage));
+                    }
 
 
-                            ConfigureWindows.GetResizeWindow.Dispatcher.Invoke(DispatcherPriority.Render, () =>
-                            {
-                                LogTextBox.Text += sb.ToString();
-                                ProgressBar.Value++;
-                                LogTextBox.ScrollToEnd();
-                                if (ProgressBar.Value == ProgressBar.Maximum)
-                                {
-                                    LogTextBox.Text += Environment.NewLine + "Completed";
-                                }
-                            });
-                        });
-                    }, cancelToken.Token).ConfigureAwait(false);
+                    ProgressBar.Maximum = thumbs.Count > 0 ? sourceFileist.Count * thumbs.Count : sourceFileist.Count;
+
+                    await BatchFunctions.RunAsync(sourceFileist, resizeAmount, quality, percentage, compress, outputFolder, toResize, LogTextBox, ProgressBar).ConfigureAwait(false);
 
 
+                    Parallel.For(0, thumbs.Count, async i =>
+                    {
+                        var thumbLoc = thumbs[i].directory + @"\" + Path.GetFileName(sourceFileist[i]);
+                        if (string.IsNullOrWhiteSpace(thumbLoc) == false)
+                        {
+                            await BatchFunctions.RunAsync(sourceFileist, thumbs[i].size, quality, thumbs[i].percentage, compress, thumbLoc, true, LogTextBox, ProgressBar).ConfigureAwait(false);
+                        }
+                    });
                 };
                 };
 
 
                 CancelButton.MouseEnter += delegate { MouseOverAnimations.ButtonMouseOverAnim(CancelText); };
                 CancelButton.MouseEnter += delegate { MouseOverAnimations.ButtonMouseOverAnim(CancelText); };
@@ -266,7 +238,7 @@ namespace PicView.Views.Windows
                 CancelButton.MouseLeave += delegate { MouseOverAnimations.ButtonMouseLeaveAnim(CancelText); };
                 CancelButton.MouseLeave += delegate { MouseOverAnimations.ButtonMouseLeaveAnim(CancelText); };
                 CancelButton.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(CancelBrush); };
                 CancelButton.MouseLeave += delegate { AnimationHelper.MouseLeaveBgTexColor(CancelBrush); };
 
 
-                CancelButton.MouseLeftButtonDown += (_, _) => { if (running) { running = false; } };
+                CancelButton.MouseLeftButtonDown += (_, _) => running = false;
             };
             };
         }
         }