Search code examples
c#.netimagemagickmagick.net

How to create black and white images in Magick.NET


I would like create TIF, PNG, JPG and BMP like black and white images via https://magick.codeplex.com.

What I found if I do like in my code I can generate only TIF black and why images but not images of other types.

Any clue how to fix it?

MagickReadSettings readSettings = new MagickReadSettings()
{
    UseMonochrome = true                    
};

using (MagickImage image = new MagickImage(fileInfo.FullName, readSettings))
{
    image.AddProfile(ColorProfile.SRGB);

    if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("tif"))
    {
        image.CompressionMethod = CompressionMethod.Group4;
        image.ColorSpace = ColorSpace.Gray;

        image.Format = MagickFormat.Tif;
    }
    else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("png"))
    {
        // image.ColorSpace = ColorSpace.Gray;
        image.Settings.SetDefine(MagickFormat.Png, "compression-strategy", "0");
        image.Settings.SetDefine(MagickFormat.Png, "compression-filter", "0");

        image.Format = MagickFormat.Png;
    }
    else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("jpg"))
    {
        image.Settings.SetDefine(MagickFormat.Jpg, "compression-strategy", "0");
        image.Settings.SetDefine(MagickFormat.Jpg, "compression-filter", "0");

        image.Format = MagickFormat.Jpg;
    }
    else  
    {
        image.CompressionMethod = CompressionMethod.NoCompression;

        image.Format = MagickFormat.Bmp;
    }

    image.Write(newFileName);
}

Solution

  • I found the answer here https://magick.codeplex.com/discussions/637181

    using (MagickImage image = new MagickImage(pathToTiffFile))
    {
        image.Threshold(60); // 60 is OK 
        image.Depth = 1;
        image.Write(pathToOutputFile);
    }