photomator/Photomator/Lib.cs

69 lines
2.3 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;
public class Lib
{
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<ConvertError[]> ConvertList(string[] src, string dest, ConvertOptions options, Action<double> setProgress)
{
double progress = 0;
List<ConvertError> unconverted = [];
await Parallel.ForEachAsync(src, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async (path, _) =>
{
string filename = path.Split(Path.DirectorySeparatorChar).Last();
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;
}