Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Keep animations between GIF and WebP
KnifeLemon7748f7aef970
diff --git a/Directory.Build.props b/Directory.Build.propsindex c49ec17b..dcd8a42a 100644--- a/Directory.Build.props+++ b/Directory.Build.props@@ -14,7 +14,7 @@parameters of a member is fine (CS1573). --><NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>- <Version>1.2.1</Version>+ <Version>1.2.2</Version><Product>Filee</Product><Authors>Filee contributors</Authors><Copyright>Copyright (c) Filee contributors</Copyright>diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex da8bbce1..abdfd873 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -68,6 +68,9 @@ current.## Images and vector graphics+- **Animations.** An animated GIF or WebP keeps every frame and its timing when converted to GIF or WebP (animated+ GIF ↔ animated WebP, lossy or lossless as the preset says) and becomes a multi-page TIFF; other targets get the first+ frame. Multi-page TIFFs and PDFs stay one image per page in WebP.- **Layered files.** PSD/PSB convert from Photoshop's composite (ImageMagick merges the layers when a file was savedwithout "maximize compatibility"). GIMP XCF layers are composited at their offsets with their blend modes; hiddenlayers are left out. ImageMagick reads 8-bit XCF without zlib tile compression (GIMP 2.10+ "better but slowerdiff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.csindex abfa6a32..ca7aa0f0 100644--- a/src/Filee.Engines/Magick/ImageEncoder.cs+++ b/src/Filee.Engines/Magick/ImageEncoder.cs@@ -36,6 +36,16 @@ internal static class ImageEncoder/// <summary>Formats that store several frames/pages in one file.</summary>private static readonly HashSet<string> MultiFrame = ["tiff", "gif"];+ /// <summary>+ /// Formats whose frames are an animation. Between these, all frames are kept with their timing (an animated GIF+ /// becomes an animated WebP and the other way round); any other target gets the first frame.+ /// </summary>+ private static readonly HashSet<string> Animated = ["gif", "webp"];++ /// <summary>True when frames of <paramref name="sourceFormat"/> are written as one animation in <paramref name="targetFormat"/>.</summary>+ public static bool KeepsAnimation(string sourceFormat, string targetFormat) =>+ Animated.Contains(sourceFormat) && Animated.Contains(targetFormat);+/// <summary>Formats without an alpha channel: transparent pixels are flattened onto the background colour.</summary>private static readonly HashSet<string> NoAlpha = ["jpg", "ppm"];@@ -84,13 +94,13 @@ internal static class ImageEncoder/// <summary>/// Chooses which frames of a (possibly multi-frame) source are converted.- /// ICO: the largest icon. GIF → single-frame target: the first frame. PSD/PSB: the composite (frame 0; any- /// further frames are layers). Otherwise: all frames/pages.+ /// ICO: the largest icon. Animated GIF/WebP: every frame for a GIF/WebP/TIFF target, else the first frame.+ /// PSD/PSB: the composite (frame 0; any further frames are layers). Otherwise: all frames/pages./// </summary>public static List<IMagickImage<byte>> SelectFrames(MagickImageCollection images, string sourceFormat, string targetFormat){- if (sourceFormat == "gif")- images.Coalesce(); // GIF frames can be partial; coalescing makes every frame a full image+ if (Animated.Contains(sourceFormat) && images.Count > 1)+ images.Coalesce(); // animation frames can be partial; coalescing makes every frame a full imagevar frames = images.ToList();if (frames.Count <= 1)@@ -99,7 +109,7 @@ internal static class ImageEncoderreturn [frames[0]];if (sourceFormat == "ico")return [frames.OrderByDescending(f => (long)f.Width * f.Height).First()];- if (sourceFormat == "gif" && !MultiFrame.Contains(targetFormat))+ if (Animated.Contains(sourceFormat) && !MultiFrame.Contains(targetFormat) && !KeepsAnimation(sourceFormat, targetFormat))return [frames[0]];return frames;}@@ -173,18 +183,19 @@ internal static class ImageEncoder}/// <summary>- /// Writes frames using the allocator. Multi-frame targets get one file; other targets get one file per frame- /// with a <c>_p{n}</c> suffix when there is more than one frame.+ /// Writes frames using the allocator. Multi-frame targets (and animations, see <see cref="KeepsAnimation"/>) get+ /// one file; other targets get one file per frame with a <c>_p{n}</c> suffix when there is more than one frame./// </summary>/// <param name="options">Options of the preset (the Netpbm sub-format depends on them).</param>/// <param name="sourcePath">Input file of the step, see <see cref="OutputFormat"/>.</param>+ /// <param name="animation">The frames are an animation: write them into one file even for a WebP target.</param>public static List<string> Write(IReadOnlyList<IMagickImage<byte>> frames, string targetFormat, IOutputAllocator output,- ImageOptions? options = null, string? sourcePath = null)+ ImageOptions? options = null, string? sourcePath = null, bool animation = false){var written = new List<string>();var (format, extension) = OutputFormat(targetFormat, options ?? new ImageOptions(), sourcePath);- if (frames.Count > 1 && MultiFrame.Contains(targetFormat))+ if (frames.Count > 1 && (MultiFrame.Contains(targetFormat) || animation)){var path = output.Allocate(extension);if (path is null)diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex e662df35..b1a43cb9 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -44,7 +44,8 @@ public sealed class MagickImageConverter : IConverter}progress?.Report(0.7);- var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath);+ var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath,+ ImageEncoder.KeepsAnimation(step.From, step.To));progress?.Report(1);return written;}, cancellationToken);diff --git a/tests/Filee.Engines.Tests/ImageAndPdfTests.cs b/tests/Filee.Engines.Tests/ImageAndPdfTests.csindex e6baf35d..b8b3f70c 100644--- a/tests/Filee.Engines.Tests/ImageAndPdfTests.cs+++ b/tests/Filee.Engines.Tests/ImageAndPdfTests.cs@@ -34,6 +34,75 @@ public class ImageAndPdfTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Equal(320u, result.Width);}+ /// <summary>A 3-frame animated GIF (red, green, blue; 20, 30 and 40 hundredths of a second, looping).</summary>+ private static string MakeAnimatedGif(string folder)+ {+ using var frames = new MagickImageCollection();+ foreach (var (color, delay) in new[] { (MagickColors.Red, 20u), (MagickColors.Lime, 30u), (MagickColors.Blue, 40u) })+ frames.Add(new MagickImage(color, 64, 48) { AnimationDelay = delay });+ var path = Path.Combine(folder, "anim.gif");+ frames.Write(path, MagickFormat.Gif);+ return path;+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public async Task Animated_gif_becomes_an_animated_webp_and_back(bool lossless)+ {+ var dir = fx.NewFolder();+ var gif = MakeAnimatedGif(dir);++ var toWebp = await fx.ConvertAsync([gif], new Preset { TargetFormat = "webp", Image = { WebpLossless = lossless } });++ AssertDone(toWebp);+ var webp = toWebp.Outputs.Single();+ using (var frames = new MagickImageCollection(webp))+ {+ Assert.Equal(3, frames.Count);+ Assert.All(frames, f => Assert.Equal(MagickFormat.WebP, f.Format));+ Assert.Equal([20u, 30u, 40u], frames.Select(f => f.AnimationDelay));+ Assert.True(frames[1].GetPixels().GetPixel(32, 24).ToColor()!.G > 200, "second frame should be green");+ }++ var back = await fx.ConvertAsync([webp], new Preset { TargetFormat = "gif", Output = { FileNamePattern = "{name}_back" } });++ AssertDone(back);+ using var again = new MagickImageCollection(back.Outputs.Single());+ Assert.Equal(3, again.Count);+ Assert.Equal([20u, 30u, 40u], again.Select(f => f.AnimationDelay));+ }++ [Fact]+ public async Task Animated_gif_to_a_still_format_takes_the_first_frame()+ {+ var dir = fx.NewFolder();+ var gif = MakeAnimatedGif(dir);++ var job = await fx.ConvertAsync([gif], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var png = new MagickImage(job.Outputs.Single());+ Assert.True(png.GetPixels().GetPixel(32, 24).ToColor()!.R > 200, "first frame is red");+ }++ [Fact]+ public async Task Multi_page_tiff_to_webp_writes_one_image_per_page()+ {+ var dir = fx.NewFolder();+ using (var pages = new MagickImageCollection())+ {+ pages.Add(new MagickImage(MagickColors.Red, 64, 48));+ pages.Add(new MagickImage(MagickColors.Blue, 64, 48));+ pages.Write(Path.Combine(dir, "pages.tiff"), MagickFormat.Tiff);+ }++ var job = await fx.ConvertAsync([Path.Combine(dir, "pages.tiff")], new Preset { TargetFormat = "webp" });++ AssertDone(job);+ Assert.Equal(2, job.Outputs.Count());+ }+[Fact]public async Task Jpg_output_flattens_transparency_and_applies_quality(){