Do you have a requirement to create GIF files dynamically? I had a similar requirement where I needed to create GIF files which will show a set of data point over a fixed time duration.
It turns out that the StackOverflow and GitHub are a great place :). There are plenty of libraries available that could help me achieve this. In the end, I picked BumpKit. I mixed its capabilities with a wonderful extension class mentioned in a StackOverflow post.
Code:
static void Main(string[] args)
{
string content = @"{
""items"":
[
{
""Value"": ""120""
},
{
""Value"": ""125""
},
{
""Value"": ""130""
},
{
""Value"": ""135""
},
{
""Value"": ""140""
}
]
}";
{
string content = @"{
""items"":
[
{
""Value"": ""120""
},
{
""Value"": ""125""
},
{
""Value"": ""130""
},
{
""Value"": ""135""
},
{
""Value"": ""140""
}
]
}";
JObject obj = JObject.Parse(content);
Console.WriteLine(obj);
Console.WriteLine(obj);
var img = Image.FromFile(@"Untitled.png");
int delay = 0;
using (GifWriter writer = new GifWriter("output.gif", 1000, -1))
{
foreach (var jItem in obj["items"])
{
delay += 1000;
string imagePath = null;
var backgroundImage = img.ScaleToFit(new Size(100, 100), false, ScalingMode.Overflow);
using (var gfx = Graphics.FromImage(backgroundImage))
{
gfx.DrawString(jItem["Value"].ToString(),
new Font(FontFamily.Families.First(f => f.Name.Contains("Times")), 15),
Brushes.White, 15, 25, 10,
new[] { Color.Black},
new[] { (float) 1 });
int delay = 0;
using (GifWriter writer = new GifWriter("output.gif", 1000, -1))
{
foreach (var jItem in obj["items"])
{
delay += 1000;
string imagePath = null;
var backgroundImage = img.ScaleToFit(new Size(100, 100), false, ScalingMode.Overflow);
using (var gfx = Graphics.FromImage(backgroundImage))
{
gfx.DrawString(jItem["Value"].ToString(),
new Font(FontFamily.Families.First(f => f.Name.Contains("Times")), 15),
Brushes.White, 15, 25, 10,
new[] { Color.Black},
new[] { (float) 1 });
gfx.DrawImage(backgroundImage, 0, 0);
}
}
writer.WriteFrame(backgroundImage, delay);
}
}
}
}
Console.ReadLine();
}
}
}
}
Untitled.png is a blank image with white background that I created using MSPaint.
Output:
You can let your imagination decide how you want to use this to create interesting gifs programmatically.
No comments:
Post a Comment