Examine animated Gif’s in C#
Recently at work, we had to find a way to examine Gif images to find out if they were animated or not. It’s a good thing to know when dealing with banner advertising. The solution was to create a method that would return a struct containing the data about the Gif we needed. This is the struct:
public struct ImageInfo
{
public int Width;
public int Height;
public bool IsAnimated;
public bool IsLooped;
public int AnimationLength; //
In milliseconds
}
>And this is the method that returns the struct when given a file name:
using
System.Drawing.Imaging;>
public static ImageInfo GetImageInfo(string path)
{
ImageInfo info
= new ImageInfo();
using (System.Drawing.Image image
= System.Drawing.Image.FromFile(path))
{
info.Height
= image.Height;
info.Width
= image.Width;
if (image.RawFormat.Equals(ImageFormat.Gif))
{
if (System.Drawing.ImageAnimator.CanAnimate(image))
{
FrameDimension frameDimension
= new FrameDimension(image.FrameDimensionsList[0]);
int frameCount
= image.GetFrameCount(frameDimension);
int delay
= 0;
int this_delay
= 0;
int index
= 0;
for (int f
= 0; f < frameCount;
f++)
{
this_delay
= BitConverter.ToInt32(image.GetPropertyItem(20736).Value,
index) * 10;
delay
+= (this_delay < 100 ? 100 :
this_delay); //
Minimum delay is 100 ms
index
+= 4;
}
info.AnimationLength
= delay;
info.IsAnimated
= true;
info.IsLooped
= BitConverter.ToInt16(image.GetPropertyItem(20737).Value, 0)
!= 1;
}
}
}
return info;
}
Example of use
Here is an example of a web page that writes the Gif info out in the response stream:
ImageInfo info
= GetImageInfo(@"c:\artists.gif");
System.Text.StringBuilder sb
= new System.Text.StringBuilder();
sb.AppendLine("animation
length: " + info.AnimationLength);
sb.AppendLine("height:
" + info.Height);
sb.AppendLine("width:
" + info.Width);
sb.AppendLine("is
animated: " + info.IsAnimated);
sb.AppendLine("is
looped: " + info.IsLooped);
Response.Write(sb.ToString().Replace(Environment.NewLine, "<br
/>"));
This is the outcome of those lines of code on a web page:
animation length: 4340
height: 81
width: 63
is animated: True
is looped: True