Search code examples
c#uwpimagemagickmagick.netimagemagick.net

Convert JPG to PNG with background transparency using ImageMagick.Net


I need to convert a JPG image to PNG and change its white background to transparent instead. I am using ImageMagick.NET and I have found the following ImageMagick command that is supposed to do what I am trying to achieve:

convert image.jpg -fuzz XX% -transparent white result.png

I have tried converting this to c# but all I am getting is a png image with a white background. My code snippet:

using (var img = new MagickImage("image.jpg"))
{
     img.Format = MagickFormat.Png;
     img.BackgroundColor = MagickColors.White;
     img.ColorFuzz = new Percentage(10);
     img.BackgroundColor = MagickColors.None;
     img.Write("image.png");
}

Any kind of help will be greatly appreciated. Thank you!!


Solution

  • Most of the arguments on the command line are either properties or method on the MagickImage class. Your command would translate to this:

    using (var img = new MagickImage("image.jpg"))
    {
        // -fuzz XX%
        img.ColorFuzz = new Percentage(10);
        // -transparent white
        img.Transparent(MagickColors.White);
        img.Write("image.png");
    }