2015-05-04 98 views
2

我在使用PictureBox控件的c#.net程序中显示了一些gif。 我想模仿Chrome浏览器,firefox等浏览器为其gif设置最小帧延迟的方式。 有一个gif有0 framedelay,并且在我的程序中显示速度非常快,但是由于浏览器设置了延迟,所以在浏览器中速度较慢。为gif设置最小帧延迟

我得到了这个代码的帧延迟率,但我不知道如何设置它。

PropertyItem item = img.GetPropertyItem(0x5100); 

我在网上找到的唯一答案并不是很详细,只是说“忽略帧速率”而不会告诉我很多。有没有办法制作我的gif副本,并明确设置帧延迟属性而不保存图像?程序的性质是动态的,因此所讨论的gif可能是任何事情,它必须灵活,所以我不能只改变一次帧延迟。

编辑:我只能想到不得不进入gif本身的二进制文件并改变它,但这似乎是一个相对简单的问题更复杂的解决方案。

回答

0

也许最简单的方法是写自己的迷你播放器:

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