Migrated from SixLabors to Magick.NET
This commit is contained in:
@@ -1,49 +1,58 @@
|
||||
using System.IO;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using ImageMagick;
|
||||
|
||||
namespace GifResizer.Models;
|
||||
|
||||
public class Gif : IDisposable
|
||||
{
|
||||
|
||||
private readonly string _path;
|
||||
private Image? _image;
|
||||
private MagickImageCollection? _images;
|
||||
|
||||
public Gif(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
if (path.Length == 0 || path.IsWhiteSpace() || !File.Exists(path))
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
throw new ArgumentException($"File '{path}' does not exist");
|
||||
_path = path;
|
||||
}
|
||||
|
||||
public void Load()
|
||||
{
|
||||
_image = Image.Load(_path);
|
||||
_images?.Dispose();
|
||||
_images = new MagickImageCollection(_path);
|
||||
_images.Coalesce();
|
||||
}
|
||||
|
||||
public void Resize(int width, int height)
|
||||
{
|
||||
if(_image == 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.");
|
||||
if(width == _image.Width && height == _image.Height) return;
|
||||
_image.Mutate(x => x.Resize(width, 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(_image == null) throw new InvalidOperationException("Image hasn't been loaded yet");
|
||||
if (_images == null)
|
||||
throw new InvalidOperationException("Image hasn't been loaded yet");
|
||||
|
||||
var directory = Path.GetDirectoryName(outputPath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
_image.Save(Path.Combine(outputPath));
|
||||
|
||||
_images.Write(outputPath);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_image?.Dispose();
|
||||
_images?.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user