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

Using Magick.NET for making PNG background transparent

Jul 11, 2016 at 11:59 AM
Hi guys,

I used convert.exe in a batch to create transparent PNG files. The parameters have been worked out after running lots of test.
convert.exe [inputfile] ( +clone -colorspace HSB -channel Saturation -separate ) ( -clone 0 -colorspace HWB -channel B -separate ) +channel ( -clone 1-2 -compose plus -composite ) -delete 1-2 -compose CopyOpacity -composite -modulate 100,2000 -level 99%,100% [outputfile]

My question: is there a way to use the .NET API to achieve the same?

Thanks
Coordinator
Jul 11, 2016 at 8:05 PM
That is possible and your command would translate to this:
using (MagickImage image = new MagickImage("wizard:")) // [inputfile]
{
  MagickImage green;

  using (MagickImage first = image.Clone()) // +clone
  {
    first.ColorSpace = ColorSpace.HSB; // -colorspace HSB
    green = first.Separate(Channels.Green).First(); // -channel Saturation -separate
  }

  MagickImage blue;

  using (MagickImage second = image.Clone()) // -clone 0
  {
    second.ColorSpace = ColorSpace.HWB; // -colorspace HWB
    blue = second.Separate(Channels.Blue).First(); // -channel B -separate
  }

  // ( -clone 1-2 -compose plus -composite ) -delete 1-2
  //
  // You don't need to clone green and blue in Magick.NET, you can just
  // use the green image and dispose the blue image.
  green.Composite(blue, CompositeOperator.Plus);
  blue.Dispose();

  image.Composite(green, CompositeOperator.CopyAlpha); // -compose CopyOpacity -composite 
  green.Dispose() // clean up the green image.

  image.Modulate(new Percentage(100), new Percentage(2000)); // -modulate 100,2000
  image.Level(new Percentage(99), new Percentage(100)); // -level 99%,100%

  image.Write("wizard.png"); // [outputfile] 
}
If one of the translations is not clear to you then feel free to ask
Jul 12, 2016 at 6:48 AM
Thanks a lot dlemstra! It looks promising and I will certainly give it a try.
Jul 19, 2016 at 9:16 AM
Hi Dirk,

I implemented the above code and it works fine but there are some distortions when the original file contains text. I attached 2 examples each of them converted with convert.exe and with Magick.NET. Can you please have a look at them and help me correct the issues?

example 1 non transparent
example 1 with convert.exe
example 1 with Magick.NET

example 2 non transparent
example 2 with convert.exe
example 2 with Magick.NET

Thanks
Coordinator
Jul 21, 2016 at 8:02 PM
IM7 does most operations on all channels, including the alpha channel. You are probably using the IM6 version of convert.exe on the command line. Only leveling the RGB channels seems to produce a better result:
image.Level(new Percentage(99), new Percentage(100), Channels.RGB);
Jul 22, 2016 at 3:06 PM
You are right, I have been using ImageMagick 6.8 for convert.exe. And lowering the blackPointPercentage parameter brought the desired result.

Thanks a lot.