Files
2026-02-17 19:38:16 +01:00

58 lines
1.5 KiB
C#

using System.IO;
using ImageMagick;
namespace GifResizer.Models;
public class Gif : IDisposable
{
private readonly string _path;
private MagickImageCollection? _images;
public Gif(string path)
{
ArgumentNullException.ThrowIfNull(path);
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
throw new ArgumentException($"File '{path}' does not exist");
_path = path;
}
public void Load()
{
_images?.Dispose();
_images = new MagickImageCollection(_path);
_images.Coalesce();
}
public void Resize(int width, int height)
{
if (_images == null)
throw new InvalidOperationException("Image hasn't been loaded yet");
if (width <= 0 || height <= 0)
throw new InvalidOperationException("Please specify a valid width or height.");
foreach (var image in _images)
{
if (image.Width == width && image.Height == height) continue;
image.Resize((uint)width, (uint)height);
}
}
public void Save(string outputPath)
{
if (_images == null)
throw new InvalidOperationException("Image hasn't been loaded yet");
var directory = Path.GetDirectoryName(outputPath);
if (!string.IsNullOrEmpty(directory))
{
Directory.CreateDirectory(directory);
}
_images.Write(outputPath);
}
public void Dispose()
{
_images?.Dispose();
}
}