Resize Animated Gif

GIF Filesystem Multiple frames Read Write Resize

Resizes animated image in GIF format.

Сode Snippet

const int width = 400;
const int height = 400;

using (var reader = new GifReader("AnimatedGif.gif"))
{
    var kX = (float)width / (float)reader.Width;
    var kY = (float)height / (float)reader.Height;

    using (var writer = new GifWriter("ResizeAnimatedGif.gif"))
    {
        // Copy general properties of the source file
        writer.BackgroundIndex = reader.BackgroundEntryIndex;
        writer.Palette = reader.Palette;
        writer.PlaybackCount = reader.PlaybackCount;

        for (int i = 0; i < reader.Frames.Count; i++)
        {
            // Read a frame
            using (var frame = (GifFrame)reader.Frames[i])
            using (var bitmap = frame.GetBitmap())
            {
                // Preserve the original palette
                ColorPalette palette = bitmap.Palette;

                // Preserve the original pixel format
                PixelFormat pixelFormat = bitmap.PixelFormat;

                // Convert the bitmap to a non-indexed format
                bitmap.ColorManagement.Convert(Aurigma.GraphicsMill.ColorSpace.Rgb, true, false);

                // Resize the bitmap in a low quality mode to prevent noise
                var newWidth = Math.Max(1, (int)((float)bitmap.Width * kX));
                var newHeight = Math.Max(1, (int)((float)bitmap.Height * kY));
                bitmap.Transforms.Resize(newWidth, newHeight, ResizeInterpolationMode.Low);

                // Return to the indexed format
                bitmap.ColorManagement.Palette = palette;
                bitmap.ColorManagement.Convert(pixelFormat);

                // Copy frame settings
                writer.FrameOptions.Left = (ushort)((float)frame.Left * kX);
                writer.FrameOptions.Top = (ushort)((float)frame.Top * kY);
                writer.FrameOptions.Delay = frame.Delay;
                writer.FrameOptions.DisposalMethod = frame.DisposalMethod;

                // Add the frame
                Pipeline.Run(bitmap + writer);
            }
        }
    }
}

Input

AnimatedGIF.gif

Output

ResizeAnimatedGif.gif

For AI-assisted development: Download Graphics Mill Code Samples XML Catalog