'How do I control the PixelFormat of images produced by magick.NET

I'm using Magick.NET-Q8-AnyCPU v8.6.1 in a .NET Framework 4.8 Winforms app to add support for image types not available in the System.Drawing namespace (e.g. WebP), and to convert images to grayscale. System.Drawing.Bitmap images have two properties that control their internal structure; PixelFormat and ImageFormat.

The MagickImage.Format maps pretty well to the ImageFormat property, but I have not been able to figure out how to map between MagickImage conversion properties and a desired Bitmap.PixelFormat property. When converting an image to png for example, I'm using:

    using (var magickImage = new MagickImage("anImage.webp")) {
    var ms = new MemoryStream();
    magickImage.Write(ms, MagickFormat.Png);
    Bitmap pngImage = new Bitmap(ms);
}

The pngImage will sometimes have a PixelFormat that matches that of 'anImage', and sometimes not. I have not been able to predict or set the PixelFormat of pngImage. How do I force the PixelFormat of the image written by magickImage.Write()?

Similarly, to convert a png image to grayscale, I'm using:

    using (var magickImage = new MagickImage("anotherImage.png")) {
    magickImage.Grayscale(PixelIntensityMethod.Brightness);
    var ms = new MemoryStream();
    magickImage.Write(ms, MagickFormat.Png);
    Bitmap grayImage = new Bitmap(ms);
}

The grayImage will have a PixelFormat of Format8bppIndexed if the magickImage.Format is Format.Gif, or Format32bppArgb for all other magickImage formats. How would I change the code to get PixelFormat.Format8bppIndexed and ImageFormat.Png?

In general, how do I control the PixelFormat of images created via Magick.NET?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source