[英]How to resize an animated gif image using C#?
Is there a method to create a copy of an animated gif image using C#?有没有一种方法可以使用 C# 创建动画 gif 图像的副本?
What I want is to generate a copy of a given gif image using the height and width parameters that the user provides.我想要的是使用用户提供的高度和宽度参数生成给定 gif 图像的副本。 I have tried for a couple of hours to accomplish this but the resulting image does not preserve the original animations.
我已经尝试了几个小时来完成此操作,但生成的图像并未保留原始动画。
Took me a while to find this, but finally found a solution:花了我一段时间才找到这个,但终于找到了解决方案:
Install Magick.NET via NuGet, license can be found here:通过 NuGet 安装Magick.NET ,可以在此处找到许可证:
https://magick.codeplex.com/license 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.根据我的测试,这适用于 alpha 通道和不同的帧速率。 Seems to be perfect!
似乎很完美!
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)万一它在将来对某人有所帮助,我发现了另一种比 Magick.NET 快得多的解决方案(在处理相同的 gif 时,它只需要 3 秒而不是 Magick.NET 需要的 50-60 秒)
PhotoSauce.MagicScaler (Only work with Windows (.NET Core and .NET 5+) and partially works on Linux ) PhotoSauce.MagicScaler (仅适用于 Windows(.NET Core 和 .NET 5+), 部分适用于 Linux )
Example:例子:
MagicImageProcessor.ProcessImage(@"\img\big.jpg", @"\img\small.jpg", new ProcessImageSettings { Width = 400 });
Resize with Bytes (Tested with png, jpg and gif):使用字节调整大小(使用 png、jpg 和 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.