A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added Image Converter to DevToys 2.0 (#979)
Etienne BAUDOUX99776fe3cb62
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 984d8f382..001db0075 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -94,6 +94,11 @@<DesignTime>True</DesignTime><AutoGen>True</AutoGen></Compile>+ <Compile Update="Tools\Graphic\ImageConverter\ImageConverter.Designer.cs">+ <DependentUpon>ImageConverter.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile><Compile Update="Tools\Test\Test.Designer.cs"><DependentUpon>Test.resx</DependentUpon><DesignTime>True</DesignTime>@@ -153,6 +158,10 @@<LastGenOutput>Graphic.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator></EmbeddedResource>+ <EmbeddedResource Update="Tools\Graphic\ImageConverter\ImageConverter.resx">+ <LastGenOutput>ImageConverter.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource><EmbeddedResource Update="Tools\Test\Test.resx"><LastGenOutput>Test.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator>diff --git a/src/app/dev/DevToys.Tools/Helpers/ImageHelper.cs b/src/app/dev/DevToys.Tools/Helpers/ImageHelper.csnew file mode 100644index 000000000..9ce99611c--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/ImageHelper.cs@@ -0,0 +1,51 @@+using DevToys.Tools.Models;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.Formats;+using SixLabors.ImageSharp.Formats.Bmp;+using SixLabors.ImageSharp.Formats.Jpeg;+using SixLabors.ImageSharp.Formats.Pbm;+using SixLabors.ImageSharp.Formats.Png;+using SixLabors.ImageSharp.Formats.Tga;+using SixLabors.ImageSharp.Formats.Tiff;+using SixLabors.ImageSharp.Formats.Webp;+using SixLabors.ImageSharp.PixelFormats;++namespace DevToys.Tools.Helpers;++internal static class ImageHelper+{+ internal static Task SaveAsync(Stream destinationStream, Image<Rgba32> image, ImageConverterSupportedFormat format, CancellationToken cancellationToken)+ {+ IImageFormat? imageFormat+ = format switch+ {+ ImageConverterSupportedFormat.BMP => BmpFormat.Instance,+ ImageConverterSupportedFormat.JPEG => JpegFormat.Instance,+ ImageConverterSupportedFormat.PBM => PbmFormat.Instance,+ ImageConverterSupportedFormat.PNG => PngFormat.Instance,+ ImageConverterSupportedFormat.TGA => TgaFormat.Instance,+ ImageConverterSupportedFormat.TIFF => TiffFormat.Instance,+ ImageConverterSupportedFormat.WEBP => WebpFormat.Instance,+ _ => null,+ };++ if (imageFormat is null)+ {+ ThrowHelper.ThrowNotSupportedException();+ }++ return image.SaveAsync(destinationStream, imageFormat, cancellationToken);+ }++ internal static async Task<Image<Rgba32>> LoadImageFromFileAsync(FileInfo file, CancellationToken cancellationToken)+ {+ using Stream inputFileStream = file.OpenRead();+ return await Image.LoadAsync<Rgba32>(inputFileStream, cancellationToken);+ }++ internal static async Task<Image<Rgba32>> LoadImageFromFileAsync(SandboxedFileReader file, CancellationToken cancellationToken)+ {+ using Stream inputFileStream = await file.GetNewAccessToFileContentAsync(cancellationToken);+ return await Image.LoadAsync<Rgba32>(inputFileStream, cancellationToken);+ }+}diff --git a/src/app/dev/DevToys.Tools/Models/ImageConverterSupportedFormat.cs b/src/app/dev/DevToys.Tools/Models/ImageConverterSupportedFormat.csnew file mode 100644index 000000000..0f29d35d3--- /dev/null+++ b/src/app/dev/DevToys.Tools/Models/ImageConverterSupportedFormat.cs@@ -0,0 +1,12 @@+namespace DevToys.Tools.Models;++internal enum ImageConverterSupportedFormat+{+ BMP,+ JPEG,+ PBM,+ PNG,+ TGA,+ TIFF,+ WEBP+}diff --git a/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.Designer.cs b/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.Designer.csindex 8149048f2..946ab22ad 100644--- a/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.Designer.cs+++ b/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.Designer.cs@@ -60,6 +60,15 @@ namespace DevToys.Tools.Strings.GlobalStrings {}}+ /// <summary>+ /// Looks up a localized string similar to Bytes.+ /// </summary>+ internal static string Bytes {+ get {+ return ResourceManager.GetString("Bytes", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to File '{0}' was not found../// </summary>@@ -77,5 +86,41 @@ namespace DevToys.Tools.Strings.GlobalStrings {return ResourceManager.GetString("FileTypeNotSupported", resourceCulture);}}++ /// <summary>+ /// Looks up a localized string similar to GB.+ /// </summary>+ internal static string Gigabytes {+ get {+ return ResourceManager.GetString("Gigabytes", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to KB.+ /// </summary>+ internal static string Kilobytes {+ get {+ return ResourceManager.GetString("Kilobytes", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to MB.+ /// </summary>+ internal static string Megabytes {+ get {+ return ResourceManager.GetString("Megabytes", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to TB.+ /// </summary>+ internal static string Terabytes {+ get {+ return ResourceManager.GetString("Terabytes", resourceCulture);+ }+ }}}diff --git a/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.resx b/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.resxindex 95e825415..8c7bb2f7d 100644--- a/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.resx+++ b/src/app/dev/DevToys.Tools/Strings/GlobalStrings/GlobalStrings.resx@@ -117,6 +117,9 @@<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>+ <data name="Bytes" xml:space="preserve">+ <value>Bytes</value>+ </data><data name="FileNotFound" xml:space="preserve"><value>File '{0}' was not found.</value><comment>{0} is a file name.</comment>@@ -125,4 +128,16 @@<value>File '{0}' is not supported. Only files of type {1} are supported.</value><comment>{0} is a file name. {1} is a list of file extensions</comment></data>+ <data name="Gigabytes" xml:space="preserve">+ <value>GB</value>+ </data>+ <data name="Kilobytes" xml:space="preserve">+ <value>KB</value>+ </data>+ <data name="Megabytes" xml:space="preserve">+ <value>MB</value>+ </data>+ <data name="Terabytes" xml:space="preserve">+ <value>TB</value>+ </data></root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.csnew file mode 100644index 000000000..c7c691683--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.Designer.cs@@ -0,0 +1,198 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.Graphic.ImageConverter {+ using System;+++ /// <summary>+ /// A strongly-typed resource class, for looking up localized strings, etc.+ /// </summary>+ // This class was auto-generated by the StronglyTypedResourceBuilder+ // class via a tool like ResGen or Visual Studio.+ // To add or remove a member, edit your .ResX file then rerun ResGen+ // with the /str option, or rebuild your VS project.+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ internal class ImageConverter {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal ImageConverter() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Graphic.ImageConverter.ImageConverter", typeof(ImageConverter).Assembly);+ resourceMan = temp;+ }+ return resourceMan;+ }+ }++ /// <summary>+ /// Overrides the current thread's CurrentUICulture property for all+ /// resource lookups using this strongly typed resource class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Image Converter tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Configuration.+ /// </summary>+ internal static string ConfigurationTitle {+ get {+ return ResourceManager.GetString("ConfigurationTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Conversion.+ /// </summary>+ internal static string ConversionTitle {+ get {+ return ResourceManager.GetString("ConversionTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select the image format to convert into.+ /// </summary>+ internal static string ConvertedFormatDescription {+ get {+ return ResourceManager.GetString("ConvertedFormatDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Delete.+ /// </summary>+ internal static string Delete {+ get {+ return ResourceManager.GetString("Delete", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Delete all.+ /// </summary>+ internal static string DeleteAll {+ get {+ return ResourceManager.GetString("DeleteAll", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Lossless image converter.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to {0:0.##} {1}.+ /// </summary>+ internal static string FileSizeDisplay {+ get {+ return ResourceManager.GetString("FileSizeDisplay", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The format to convert images to.+ /// </summary>+ internal static string FormatOptionDescription {+ get {+ return ResourceManager.GetString("FormatOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to A set of image file paths or directories that contain images to convert.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Image Converter.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Directory where the result should be persisted, or a single file path, if the input is also a single file path..+ /// </summary>+ internal static string OutputDirectoryOptionDescription {+ get {+ return ResourceManager.GetString("OutputDirectoryOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Save all.+ /// </summary>+ internal static string SaveAll {+ get {+ return ResourceManager.GetString("SaveAll", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Save as.+ /// </summary>+ internal static string SaveAs {+ get {+ return ResourceManager.GetString("SaveAs", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Image Converter.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resxnew file mode 100644index 000000000..92500cd09--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverter.resx@@ -0,0 +1,166 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>Image Converter tool</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="ConversionTitle" xml:space="preserve">+ <value>Conversion</value>+ </data>+ <data name="ConvertedFormatDescription" xml:space="preserve">+ <value>Select the image format to convert into</value>+ </data>+ <data name="Delete" xml:space="preserve">+ <value>Delete</value>+ </data>+ <data name="DeleteAll" xml:space="preserve">+ <value>Delete all</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Lossless image converter</value>+ </data>+ <data name="FileSizeDisplay" xml:space="preserve">+ <value>{0:0.##} {1}</value>+ <comment>{0} is a decimal number representing a file size. {1} is a unit, like Bytes, KB, MB, GB, TB</comment>+ </data>+ <data name="FormatOptionDescription" xml:space="preserve">+ <value>The format to convert images to</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>A set of image file paths or directories that contain images to convert</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>Image Converter</value>+ </data>+ <data name="OutputDirectoryOptionDescription" xml:space="preserve">+ <value>Directory where the result should be persisted, or a single file path, if the input is also a single file path.</value>+ </data>+ <data name="SaveAll" xml:space="preserve">+ <value>Save all</value>+ </data>+ <data name="SaveAs" xml:space="preserve">+ <value>Save as</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>Image Converter</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterCommandLineTool.csnew file mode 100644index 000000000..b8d2bf71d--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterCommandLineTool.cs@@ -0,0 +1,126 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;+using OneOf;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;++namespace DevToys.Tools.Tools.Graphic.ImageConverter;++[Export(typeof(ICommandLineTool))]+[Name("ImageConverter")]+[CommandName(+ Name = "imageconverter",+ Alias = "imgconv",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Graphic.ImageConverter.ImageConverter",+ DescriptionResourceName = nameof(ImageConverter.Description))]+internal sealed class ImageConverterCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(ImageConverter.InputOptionDescription))]+ internal OneOf<DirectoryInfo, FileInfo>[] Input { get; set; } = null!;++ [CommandLineOption(+ Name = "type",+ Alias = "t",+ IsRequired = true,+ DescriptionResourceName = nameof(ImageConverter.FormatOptionDescription))]+ internal ImageConverterSupportedFormat Format { get; set; }++ [CommandLineOption(+ Name = "output",+ Alias = "o",+ DescriptionResourceName = nameof(ImageConverter.OutputDirectoryOptionDescription))]+ internal OneOf<DirectoryInfo, FileInfo>? Output { get; set; }++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ try+ {+ if (Input is null || Input.Length == 0)+ {+ return -1;+ }++ if (Input.Length >= 1)+ {+ if (Output.HasValue && Output.Value.IsT1)+ {+ Console.Error.WriteLine("Output must be a directory when passing more than one file as input.");+ return -1;+ }+ }++ for (int i = 0; i < Input.Length; i++)+ {+ await TreatDirectoryOrFileAsync(Input[i], logger, cancellationToken);+ }++ return 0;+ }+ catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException)+ {+ return -1;+ }+ catch+ {+ // TODO: Log exception.+ return -1;+ }+ }++ private async Task TreatDirectoryOrFileAsync(OneOf<DirectoryInfo, FileInfo> directoryOrFile, ILogger logger, CancellationToken cancellationToken)+ {+ if (directoryOrFile.IsT0)+ {+ foreach (FileInfo fileInDirectory in directoryOrFile.AsT0.EnumerateFiles())+ {+ await TreatDirectoryOrFileAsync(fileInDirectory, logger, cancellationToken);+ }+ }+ else if (directoryOrFile.IsT1)+ {+ cancellationToken.ThrowIfCancellationRequested();++ if (StaticImageFileDataTypeDetector.SupportedFileTypes.Contains(directoryOrFile.AsT1.Extension, StringComparer.OrdinalIgnoreCase))+ {+ await ConvertAsync(directoryOrFile.AsT1, cancellationToken);+ }+ }+ }++ private async Task ConvertAsync(FileInfo fileToConvert, CancellationToken cancellationToken)+ {+ FileInfo outputFile;+ if (!Output.HasValue || Output.Value.IsT0)+ {+ string outputDirectoryPath;+ if (Output.HasValue)+ {+ outputDirectoryPath = Output.Value.AsT0.FullName;+ }+ else+ {+ outputDirectoryPath = Path.GetDirectoryName(fileToConvert.FullName)!;+ }++ string outputFileName = Path.GetFileNameWithoutExtension(fileToConvert.FullName) + "." + Format.ToString().ToLower();+ string outputFilePath = Path.Combine(outputDirectoryPath, outputFileName);+ outputFile = new FileInfo(outputFilePath);+ }+ else+ {+ outputFile = Output.Value.AsT1;+ }++ // Load the image first, in case if the user will overwrite it.+ using Image<Rgba32> originalImage = await ImageHelper.LoadImageFromFileAsync(fileToConvert, cancellationToken);++ using FileStream outputFileStream = File.Create(outputFile.FullName);+ await ImageHelper.SaveAsync(outputFileStream, originalImage, Format, cancellationToken);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterGuiTool.csnew file mode 100644index 000000000..335276dec--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterGuiTool.cs@@ -0,0 +1,219 @@+using System.Collections.Specialized;+using DevToys.Tools.Models;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;++namespace DevToys.Tools.Tools.Graphic.ImageConverter;++[Export(typeof(IGuiTool))]+[Name("ImageConverter")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0127',+ GroupName = PredefinedCommonToolGroupNames.Graphic,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Graphic.ImageConverter.ImageConverter",+ ShortDisplayTitleResourceName = nameof(ImageConverter.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(ImageConverter.LongDisplayTitle),+ DescriptionResourceName = nameof(ImageConverter.Description),+ AccessibleNameResourceName = nameof(ImageConverter.AccessibleName))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Image)]+[AcceptedDataTypeName("StaticImageFile")]+[AcceptedDataTypeName("StaticImageFiles")]+internal sealed class ImageConverterGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// The image format to convert into.+ /// </summary>+ private static readonly SettingDefinition<ImageConverterSupportedFormat> targetImageFormat+ = new(+ name: $"{nameof(ImageConverterGuiTool)}.{nameof(targetImageFormat)}",+ defaultValue: ImageConverterSupportedFormat.PNG);++ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IFileStorage _fileStorage;+ private readonly IUIList _itemList = List("image-converter-task-list");+ private readonly IUIButton _saveAllButton = Button("image-converter-save-all-button");+ private readonly IUIButton _deleteAllButton = Button("image-converter-delete-all-button");++ [ImportingConstructor]+ public ImageConverterGuiTool(ISettingsProvider settingsProvider, IFileStorage fileStorage)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;+ _fileStorage = fileStorage;++ _itemList.Items.CollectionChanged += OnItemListItemsChanged;+ }++ internal ImageConverterSupportedFormat UserSelectedImageFormat => _settingsProvider.GetSetting(targetImageFormat);++ internal IUIList ItemList => _itemList;++ public UIToolView View+ => new(+ isScrollable: true,+ Stack()+ .Vertical()+ .LargeSpacing()++ .WithChildren(+ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(ImageConverter.ConfigurationTitle),++ Setting("image-converter-target-format-type-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(ImageConverter.ConversionTitle)+ .Description(ImageConverter.ConvertedFormatDescription)++ .Handle(+ _settingsProvider,+ targetImageFormat,+ onOptionSelected: null,+ Item(ImageConverterSupportedFormat.BMP),+ Item(ImageConverterSupportedFormat.JPEG),+ Item(ImageConverterSupportedFormat.PBM),+ Item(ImageConverterSupportedFormat.PNG),+ Item(ImageConverterSupportedFormat.TGA),+ Item(ImageConverterSupportedFormat.TIFF),+ Item(ImageConverterSupportedFormat.WEBP))),++ FileSelector()+ .CanSelectManyFiles()+ .LimitFileTypesTo(StaticImageFileDataTypeDetector.SupportedFileTypes)+ .OnFilesSelected(OnFilesSelected),++ Stack()+ .Horizontal()+ .AlignHorizontally(UIHorizontalAlignment.Right)+ .MediumSpacing()++ .WithChildren(+ _saveAllButton+ .Icon("FluentSystemIcons", '\uF67F')+ .Text(ImageConverter.SaveAll)+ .AccentAppearance()+ .Disable()+ .OnClick(OnSaveAllAsync),++ _deleteAllButton+ .Icon("FluentSystemIcons", '\uF34C')+ .Text(ImageConverter.DeleteAll)+ .Disable()+ .OnClick(OnDeleteAllAsync)),++ _itemList+ .ForbidSelectItem()));++ public async void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Image && parsedData is Image<Rgba32> image)+ {+ FileInfo temporaryFile = _fileStorage.CreateSelfDestroyingTempFile("png");++ using (image)+ {+ using Stream fileStream = _fileStorage.OpenWriteFile(temporaryFile.FullName, replaceIfExist: true);+ await image.SaveAsPngAsync(fileStream);+ }++ _itemList.Items.Insert(0, new ImageConverterTaskItemGui(this, SandboxedFileReader.FromFileInfo(temporaryFile), _fileStorage));+ }+ else if (dataTypeName == "StaticImageFile" && parsedData is FileInfo file)+ {+ _itemList.Items.Insert(0, new ImageConverterTaskItemGui(this, SandboxedFileReader.FromFileInfo(file), _fileStorage));+ }+ else if (dataTypeName == "StaticImageFiles" && parsedData is FileInfo[] files)+ {+ for (int i = 0; i < files.Length; i++)+ {+ _itemList.Items.Insert(0, new ImageConverterTaskItemGui(this, SandboxedFileReader.FromFileInfo(files[i]), _fileStorage));+ }+ }+ }++ public void Dispose()+ {+ for (int i = 0; i < _itemList.Items.Count; i++)+ {+ if (_itemList.Items[i] is IDisposable disposableItem)+ {+ disposableItem.Dispose();+ }+ }++ _itemList.Items.CollectionChanged -= OnItemListItemsChanged;+ }++ private void OnFilesSelected(SandboxedFileReader[] files)+ {+ for (int i = 0; i < files.Length; i++)+ {+ _itemList.Items.Insert(+ 0,+ new ImageConverterTaskItemGui(this, files[i], _fileStorage));+ }+ }++ private async ValueTask OnSaveAllAsync()+ {+ string? folderPath = await _fileStorage.PickFolderAsync();++ if (!string.IsNullOrEmpty(folderPath))+ {+ ImageConverterSupportedFormat targetFormat = UserSelectedImageFormat;+ for (int i = 0; i < _itemList.Items.Count; i++)+ {+ if (_itemList.Items[i] is ImageConverterTaskItemGui item)+ {+ string newFileName = Path.GetFileNameWithoutExtension(item.InputFile.FileName) + "." + targetFormat.ToString().ToLower();+ string newFilePath = Path.Combine(folderPath, newFileName);+ await item.SaveAsync(newFilePath, targetFormat);+ }+ }+ }+ }++ private ValueTask OnDeleteAllAsync()+ {+ for (int i = 0; i < _itemList.Items.Count; i++)+ {+ if (_itemList.Items[i] is IDisposable disposableItem)+ {+ disposableItem.Dispose();+ }+ }++ _itemList.Items.Clear();++ return ValueTask.CompletedTask;+ }++ private void OnItemListItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ UpdateButtonsState();+ }++ private void UpdateButtonsState()+ {+ bool hasItems = _itemList.Items.Count > 0;+ if (hasItems)+ {+ _saveAllButton.Enable();+ _deleteAllButton.Enable();+ }+ else+ {+ _saveAllButton.Disable();+ _deleteAllButton.Disable();+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterTaskItemGui.cs b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterTaskItemGui.csnew file mode 100644index 000000000..528bb4fdb--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Graphic/ImageConverter/ImageConverterTaskItemGui.cs@@ -0,0 +1,142 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.Tools.Strings.GlobalStrings;+using SixLabors.ImageSharp;+using SixLabors.ImageSharp.PixelFormats;++namespace DevToys.Tools.Tools.Graphic.ImageConverter;++internal sealed class ImageConverterTaskItemGui : IUIListItem, IDisposable+{+ public static readonly string[] SizesStrings+ = {+ GlobalStrings.Bytes,+ GlobalStrings.Kilobytes,+ GlobalStrings.Megabytes,+ GlobalStrings.Gigabytes,+ GlobalStrings.Terabytes+ };++ private enum GridRows+ {+ Top,+ Bottom+ }++ private enum GridColumns+ {+ Progress,+ FileNameAndOriginalSize,+ CompressedSize,+ ActionButtons+ }++ private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();+ private readonly IFileStorage _fileStorage;+ private readonly Lazy<IUIElement> _ui;+ private readonly IUISetting _setting = Setting();+ private readonly ImageConverterGuiTool _imageConverterGuiTool;++ internal ImageConverterTaskItemGui(ImageConverterGuiTool imageConverterGuiTool, SandboxedFileReader inputFile, IFileStorage fileStorage)+ {+ Guard.IsNotNull(imageConverterGuiTool);+ Guard.IsNotNull(inputFile);+ Guard.IsNotNull(fileStorage);++ _imageConverterGuiTool = imageConverterGuiTool;+ _fileStorage = fileStorage;+ Value = inputFile;+ InputFile = inputFile;++ ComputePropertiesAsync().ForgetSafely();++ _ui+ = new Lazy<IUIElement>(+ _setting+ .Icon("FluentSystemIcons", '\uF488')+ .Title(inputFile.FileName)++ .InteractiveElement(+ Stack()+ .Horizontal()+ .MediumSpacing()++ .WithChildren(+ Stack()+ .Horizontal()+ .SmallSpacing()++ .WithChildren(+ Button()+ .Icon("FluentSystemIcons", '\uF67F')+ .OnClick(OnSaveAsAsync),+ Button()+ .Icon("FluentSystemIcons", '\uF34C')+ .OnClick(OnDeleteAsync)))));+ }++ public IUIElement UIElement => _ui.Value;++ public object? Value { get; }++ internal SandboxedFileReader InputFile { get; }++ public void Dispose()+ {+ _cancellationTokenSource.Cancel();+ _cancellationTokenSource.Dispose();+ InputFile.Dispose();+ }++ internal async Task SaveAsync(string filePath, ImageConverterSupportedFormat format)+ {+ using Image<Rgba32> originalImage = await ImageHelper.LoadImageFromFileAsync(InputFile, _cancellationTokenSource.Token);++ using FileStream outputFileStream = File.Create(filePath);+ await ImageHelper.SaveAsync(outputFileStream, originalImage, format, _cancellationTokenSource.Token);+ }++ private async ValueTask OnSaveAsAsync()+ {+ // Load the image first, in case if the user will overwrite it (so we can read it before PickSaveFileAsync opens an access to the file).+ using Image<Rgba32> originalImage = await ImageHelper.LoadImageFromFileAsync(InputFile, _cancellationTokenSource.Token);++ // Ask the user to pick up a file.+ Stream? outputFileStream = await _fileStorage.PickSaveFileAsync(_imageConverterGuiTool.UserSelectedImageFormat.ToString());+ if (outputFileStream is not null)+ {+ await ImageHelper.SaveAsync(outputFileStream, originalImage, _imageConverterGuiTool.UserSelectedImageFormat, _cancellationTokenSource.Token);+ }+ }++ private ValueTask OnDeleteAsync()+ {+ _imageConverterGuiTool.ItemList.Items.Remove(this);+ return ValueTask.CompletedTask;+ }++ private async Task ComputePropertiesAsync()+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(_cancellationTokenSource.Token);++ using Stream fileStream = await InputFile.GetNewAccessToFileContentAsync(_cancellationTokenSource.Token);++ long storageFileSize = fileStream.Length;+ string? fileSize = HumanizeFileSize(storageFileSize, ImageConverter.FileSizeDisplay);++ _setting.Description(fileSize);+ }++ private static string HumanizeFileSize(double fileSize, string fileSizeDisplay)+ {+ int order = 0;+ while (fileSize >= 1024 && order < SizesStrings.Length - 1)+ {+ order++;+ fileSize /= 1024;+ }++ string fileSizeString = string.Format(fileSizeDisplay, fileSize, SizesStrings[order]);+ return fileSizeString;+ }+}