using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Webp; using SixLabors.ImageSharp.Processing; using System.Runtime.InteropServices; namespace Photomator; public static class Lib { const int SW_HIDE = 0; const int SW_SHOW = 5; readonly static IntPtr handle = GetConsoleWindow(); [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd,int nCmdShow); public static void HideConsole() { ShowWindow(handle,SW_HIDE); } public static void ShowConsole() { ShowWindow(handle,SW_SHOW); } public static async Task Convert(string src, string dest, ConvertOptions options) { Image img = await Image.LoadAsync(src); img.Mutate(i => { i.AutoOrient(); Size currentSize = i.GetCurrentSize(); if (currentSize.Height > currentSize.Width) { i.Resize(options.Resolution, 0); } else { i.Resize(0, options.Resolution); } }); await img.SaveAsWebpAsync(dest, new WebpEncoder { FileFormat = options.Format }); } public static async Task ConvertList(string[] src, string dest, ConvertOptions options, Action setProgress) { double progress = 0; List unconverted = []; await Parallel.ForEachAsync(src, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async (path, _) => { string filename = path.Split(Path.DirectorySeparatorChar)[^1]; string[] splitted = filename.Split('.'); splitted[^1] = "webp"; try { await Convert(path, dest + Path.DirectorySeparatorChar + string.Join(".", splitted), options); } catch (UnknownImageFormatException) { unconverted.Add(new ConvertError(filename, "Das Dateiformat wird nicht unterstützt.")); } catch (Exception e) { unconverted.Add(new ConvertError(filename, e.Message)); } progress += 1.0 / src.Length; setProgress(progress); }); return [.. unconverted]; } } public readonly struct ConvertOptions(string? resolution, uint format) { public int Resolution { get; init; } = resolution != null ? Convert.ToInt32(resolution) : 1440; public WebpFileFormatType Format { get; init; } = format == 1 ? WebpFileFormatType.Lossless : WebpFileFormatType.Lossy; } public readonly struct ConvertError(string file, string message) { public string File { get; init; } = file; public string Message { get; init; } = message; }