This project has moved. For the latest updates, please go here.

C# Replacing a transparent background with White

Sep 2, 2014 at 7:43 PM
Hi,
I am trying to read an image file (which might be PNG, JPG,, or GIF) and, if it has a transparent background change the background to White, then resize it and writing it out as a GIF file while maintaining the highest quality possible.
I know the code below isn't quite right, I've tried various iterations but been unable to get the background color to change. Any help/suggestions appreciated.
Thanks
MagickImage img = new MagickImage(source);
img.BackgroundColor = new MagickColor(System.Drawing.Color.White);
MagickGeometry geometry = new MagickGeometry(width, height);
geometry.IsPercentage = false;
//geometry.IgnoreAspectRatio = false;
img.Quality = 100;
img.Resize(geometry);
img.Write(target);
Coordinator
Sep 2, 2014 at 9:42 PM
Edited Sep 2, 2014 at 9:43 PM
Setting the background color does not change it. If you want to change the transparent pixels to a solid color you should do the following:
using(MagickImage img = new MagickImage(source))
{
  // There is an implicit cast from Drawing.Color to MagickColor
  img.ColorAlpha(System.Drawing.Color.White);
  img.Quality = 100;
  img.Resize(width, height);
  img.Write(target);
}
p.s. you don't need to set geometry.IsPercentage to false. This is the default.
Sep 2, 2014 at 11:11 PM
Perfect! Thanks!