I'm trying to create a countdown GIF using the Magick.Net library.
Although the code is working correct I came up with an issue last week.
When merging some text frames with a transparent background onto a background image, depending on the color of the background image, the result is different.
When adding the text on a white background, the transparency becomes a certain shade of pink, when adding the text frames on a dark background (e.g. blue), the transparency is perfect.
Does anyone have some pointers on this?
- Is this a known issue/bug?
- Is this a configuration error
- ...
Regards,
Erwin
Code: Select all
namespace GifGenerator
{
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using ImageMagick;
class Program
{
static MagickColor textBackgroundColor = MagickColor.Transparent;
static MagickColor textColor = new MagickColor(Color.Black);
static MagickGeometry area = new MagickGeometry(10, 10, 20, 20);
static void Main(string[] args)
{
// intialize background images
MagickImage whiteBackgroundImage = new MagickImage(@"BackgroundImages\White background.png");
whiteBackgroundImage.Quantize(new QuantizeSettings() { Colors = 255 });
MagickImage blueBackgroundImage = new MagickImage(@"BackgroundImages\Blue background.png");
blueBackgroundImage.Quantize(new QuantizeSettings() { Colors = 255 });
File.WriteAllBytes(@"BackgroundIMages\White Background.gif", GenerateGif(whiteBackgroundImage));
File.WriteAllBytes(@"BackgroundIMages\Blue Background.gif", GenerateGif(blueBackgroundImage));
}
private static byte[] GenerateGif(MagickImage backgroundImage)
{
MagickImageCollection collection = new MagickImageCollection();
collection.AddRange(GenerateFrames(backgroundImage, 10));
byte[] data = collection.ToByteArray(MagickFormat.Gif);
return data;
}
private static IEnumerable<MagickImage> GenerateFrames(MagickImage backgroundImage, int numberOfFrames)
{
for (int i = 0; i < numberOfFrames; i++)
{
MagickImage textImage = new MagickImage(MagickColor.Transparent, 20, 20);
WriteText(textImage, i.ToString(), textBackgroundColor, textColor, "Arial", 14);
// render gif
MagickImage partialFrame = backgroundImage.Clone(area);
partialFrame.Composite(textImage, CompositeOperator.Over);
partialFrame.Alpha(AlphaOption.Off);
partialFrame.Page = area;
partialFrame.GifDisposeMethod = GifDisposeMethod.None;
partialFrame.Quantize(new QuantizeSettings() { Colors = 255 });
MagickImage frame = new MagickImage(backgroundImage);
frame.Composite(partialFrame, partialFrame.Page, CompositeOperator.Over);
yield return frame;
}
}
private static void WriteText(MagickImage image, string text, MagickColor backgroundColor, MagickColor fontColor, string fontFamily, double fontSize)
{
image.BackgroundColor = backgroundColor;
image.FillColor = fontColor;
image.Font = fontFamily.Replace(" ", "-");
image.FontPointsize = fontSize * 96.0 / 72.0;
image.Read(string.Format(CultureInfo.InvariantCulture, "label:{0}", text));
}
}
}