2015-05-04 60 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