How to resize an animated gif image using C#?
Asked Answered
J

3

8

Is there a method to create a copy of an animated gif image using C#?

What I want is to generate a copy of a given gif image using the height and width parameters that the user provides. I have tried for a couple of hours to accomplish this but the resulting image does not preserve the original animations.

Jerroldjerroll answered 11/2, 2009 at 22:1 Comment(1)
You mean resize correct? – Cartierbresson
S
4

You need to loop through the frames in the animated GIF and resize each one.

May also want to take a look at GifLib.

Sex answered 11/2, 2009 at 22:19 Comment(0)
E
6

Took me a while to find this, but finally found a solution:

Install Magick.NET via NuGet, license can be found here:
https://magick.codeplex.com/license

Example code:

var newWidth = 100;
using (var collection = new MagickImageCollection(new FileInfo(@"C:\test.gif")))
{
    collection.Coalesce();
    foreach (var image in collection)
    {
        image.Resize(newWidth, 0);
    }
    collection.Write(@"c:\resized.gif");
}

From my tests, this works with alpha channels and varying frame rates. Seems to be perfect!

Emmalineemmalyn answered 3/1, 2017 at 11:32 Comment(1)
I had to remove the call to Coalesce() to get this to work. Also, if you want to resize locally, replace Write() with ToBitmap(ImageFormate.Gif). Also, this is extremely slow. Not recommended for real-time applications where speed is needed. – Craquelure
S
4

You need to loop through the frames in the animated GIF and resize each one.

May also want to take a look at GifLib.

Sex answered 11/2, 2009 at 22:19 Comment(0)
S
2

In case it helps someone in the future, I have found another solution that is much faster than Magick.NET (in processing the same gif, it takes only 3s instead of 50-60s than Magick.NET takes)

PhotoSauce.MagicScaler (Only work with Windows (.NET Core and .NET 5+) and partially works on Linux)

Example:

MagicImageProcessor.ProcessImage(@"\img\big.jpg", @"\img\small.jpg", new ProcessImageSettings { Width = 400 });

Resize with Bytes (Tested with png, jpg and gif):

public static byte[] ResizeImageBytes(byte[] imageBytes, int newWidth, int newHeight) {
    using (MemoryStream outStream = new()) {
        ProcessImageSettings processImageSettings = new() {
            Width = newWidth,
            Height = newHeight,
            ResizeMode = CropScaleMode.Stretch,
            HybridMode = HybridScaleMode.Turbo
        };
        MagicImageProcessor.ProcessImage(imageBytes, outStream, processImageSettings);
        return outStream.ToArray();
    }
}
Side answered 6/6, 2022 at 12:42 Comment(2)
This is much faster than Magick.NET. Thx. – Financier
I didn't bother trying anything else as this worked a treat first time. Thank you. Oh... And thanks also for the ReziseImageBytes() method. Exactly what I required. πŸ‘ – Bahadur

© 2022 - 2024 β€” McMap. All rights reserved.