photomator/Photomator/Lib.cs

53 lines
2.2 KiB
C#
Raw Normal View History

2024-09-08 22:37:06 +02:00
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Webp;
using SixLabors.ImageSharp.Processing;
namespace Photomator;
2024-09-14 17:49:20 +02:00
public static class Lib {
public static async Task Convert(string src, string dest, ConvertOptions options) {
2024-09-08 22:37:06 +02:00
Image img = await Image.LoadAsync(src);
2024-09-14 17:49:20 +02:00
img.Mutate(i => {
2024-09-08 22:37:06 +02:00
i.AutoOrient();
Size currentSize = i.GetCurrentSize();
2024-09-14 17:49:20 +02:00
if (currentSize.Height > currentSize.Width) {
2024-09-08 22:37:06 +02:00
i.Resize(options.Resolution, 0);
2024-09-14 17:49:20 +02:00
} else {
2024-09-08 22:37:06 +02:00
i.Resize(0, options.Resolution);
}
});
2024-09-14 17:49:20 +02:00
await img.SaveAsWebpAsync(dest, new WebpEncoder {
2024-09-08 22:37:06 +02:00
FileFormat = options.Format
});
}
2024-09-14 17:49:20 +02:00
public static async Task<ConvertError[]> ConvertList(string[] src, string dest, ConvertOptions options, Action<double> setProgress) {
2024-09-08 22:37:06 +02:00
double progress = 0;
List<ConvertError> unconverted = [];
2024-09-14 17:49:20 +02:00
await Parallel.ForEachAsync(src, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async (path, _) => {
string filename = path.Split(Path.DirectorySeparatorChar)[^1];
2024-09-08 22:37:06 +02:00
string[] splitted = filename.Split('.');
splitted[^1] = "webp";
2024-09-14 17:49:20 +02:00
try {
2024-09-08 22:37:06 +02:00
await Convert(path, dest + Path.DirectorySeparatorChar + string.Join(".", splitted), options);
2024-09-14 17:49:20 +02:00
} catch (UnknownImageFormatException) {
2024-09-08 22:37:06 +02:00
unconverted.Add(new ConvertError(filename, "Das Dateiformat wird nicht unterstützt."));
2024-09-14 17:49:20 +02:00
} catch (Exception e) {
2024-09-08 22:37:06 +02:00
unconverted.Add(new ConvertError(filename, e.Message));
}
progress += 1.0 / src.Length;
setProgress(progress);
});
return [.. unconverted];
}
}
2024-09-14 17:49:20 +02:00
public readonly struct ConvertOptions(string? resolution, uint format) {
2024-09-08 22:37:06 +02:00
public int Resolution { get; init; } = resolution != null ? Convert.ToInt32(resolution) : 1440;
public WebpFileFormatType Format { get; init; } = format == 1 ? WebpFileFormatType.Lossless : WebpFileFormatType.Lossy;
}
2024-09-14 17:49:20 +02:00
public readonly struct ConvertError(string file, string message) {
2024-09-08 22:37:06 +02:00
public string File { get; init; } = file;
public string Message { get; init; } = message;
}