我正在使用PictureBox控件在c#.net程序中显示一些gif。
我想模仿chrome,firefox等浏览器为其gif设置最小帧延迟的方式。
有一个gif的帧延迟为0,在我的程序中显示得非常快,但是在浏览器中却很慢,因为浏览器设置了延迟。
我正在用此代码获得帧延迟率,但是我不知道如何设置它。
PropertyItem item = img.GetPropertyItem(0x5100);
我在网上找到的唯一答案还不是很详细,只需说“忽略帧速率”就无需多说。有没有办法复制我的gif文件并显式设置帧延迟属性而不保存图像?程序的性质是动态的,因此所讨论的gif可能是任何东西,而且必须灵活,因此我不能只更改一次帧延迟。
编辑:我只能想到必须进入gif本身的二进制文件并在那里进行更改,但这似乎是一个相对简单的问题的更复杂的解决方案。
最佳答案
也许最简单的方法是编写自己的迷你播放器:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private AnimatedGif _animatedGif;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_animatedGif = new AnimatedGif(@"..\..\playing-cards.gif");
}
private async void button1_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
var animatedGif = _animatedGif;
var frames = animatedGif.Frames;
for (var i = 0; i < frames; i++)
{
var image = animatedGif.GetFrame(i);
pictureBox1.Image = image;
var millisecondsTimeout = animatedGif.Durations[i] * 10;
Thread.Sleep(millisecondsTimeout);
}
});
}
}
internal class AnimatedGif
{
public AnimatedGif(string filename)
{
if (filename == null) throw new ArgumentNullException("filename");
var image = Image.FromFile(filename);
var item = image.PropertyItems.SingleOrDefault(s => s.Id == 0x5100);
if (item == null) throw new ArgumentNullException("filename");
var frames = item.Value.Length / 4;
var durations = new int[frames];
for (var i = 0; i < frames; i++)
{
durations[i] = BitConverter.ToInt32(item.Value, i * 4);
}
Frames = frames;
Durations = durations;
Image = image;
}
public Image Image { get; set; }
public int Frames { get; set; }
public int[] Durations { get; set; }
public Image GetFrame(int index)
{
var activeFrame = Image.SelectActiveFrame(FrameDimension.Time, index);
if (activeFrame != 0) return null;
var bitmap = new Bitmap(Image);
return bitmap;
}
}
}
然后通过考虑循环,背景等来改善它。这些属性的ID在这里说明:Property Item Descriptions
关于c# - 设置gif的最小帧延迟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30022952/