BitmapSourceExtensionsConvertPixelFormat(BitmapSource, PixelFormat, IQuantizer, IDitherer) Method

Converts the specified bitmap to a WriteableBitmap with the desired PixelFormat.

Definition

Namespace: KGySoft.Drawing.Wpf
Assembly: KGySoft.Drawing.Wpf (in KGySoft.Drawing.Wpf.dll) Version: 7.2.0
C#
public static WriteableBitmap ConvertPixelFormat(
	this BitmapSource bitmap,
	PixelFormat newPixelFormat,
	IQuantizer? quantizer,
	IDitherer? ditherer = null
)

Parameters

bitmap  BitmapSource
The original bitmap to convert.
newPixelFormat  PixelFormat
The desired new pixel format.
quantizer  IQuantizer
An optional IQuantizer instance to determine the colors of the result. If and newPixelFormat is an indexed format, then a default palette and quantization logic will be used.
ditherer  IDitherer  (Optional)
The ditherer to be used. Might be ignored if quantizer is not specified and newPixelFormat represents an at least 24 bits-per-pixel size. This parameter is optional.
Default value: .

Return Value

WriteableBitmap
A new WriteableBitmap instance with the desired pixel format.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type BitmapSource. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

Remarks

  Note

An unmatching quantizer and newPixelFormat may cause undesired results.

The ditherer may have no effect if the quantizer uses too many colors.

To produce a result with up to 256 colors best optimized for the source bitmap you can use the OptimizedPaletteQuantizer class.

To quantize a WriteableBitmap in place, without changing the pixel format you can use the BitmapDataExtensions.Quantize method. You can use the GetReadWriteBitmapData extension method to obtain an IReadWriteBitmapData for a WriteableBitmap.

To dither a WriteableBitmap in place, without changing the pixel format you can use the BitmapDataExtensions.Dither method. You can use the GetReadWriteBitmapData extension method to obtain an IReadWriteBitmapData for a WriteableBitmap.

Example

The following example demonstrates the possible results of this method compared to using WPF's FormatConvertedBitmap class:
C#
public static BitmapSource Convert(BitmapSource source, PixelFormat targetPixelFormat, IQuantizer quantizer, IDitherer ditherer)
{
    // a.) by KGy SOFT: can use a specific quantizer and ditherer.
    //     Back color and alpha threshold is specified by the quantizer
    return source.ConvertPixelFormat(targetPixelFormat, quantizer, ditherer);

    // b.) by WPF: If no palette is specified, then optimizes colors for indexed images.
    //     No back color is used, alpha colors above the threshold suffer from color bleeding.
    //     A fixed ditherer is always applied to <= 8 bpp formats (but not for Bgr555, for example)
    GetQuantizerData(out BitmapPalette? palette, out double alphaThreshold);
    return new FormatConvertedBitmap(source, targetPixelFormat, palette, alphaThreshold);

    // Extracting the possible palette and alpha threshold for the WPF conversion from the quantizer
    void GetQuantizerData(out BitmapPalette? palette, out double alphaThreshold)
    {
        using IReadableBitmapData bitmapData = source.GetReadableBitmapData();
        using IQuantizingSession session = quantizer.Initialize(bitmapData); // can be slow for OptimizedPaletteQuantizer
        IList<Color>? colors = session.Palette?.GetEntries().Select(c => Color.FromArgb(c.A, c.R, c.G, c.B)).ToList();
        palette = colors == null ? null : new BitmapPalette(colors);
        alphaThreshold = session.AlphaThreshold / 255d * 100d;
    }
}
Original image
Converted image

Color hues with alpha gradient
Color hues with alpha gradient

Alpha gradient converted to indexed 8 bit format by KGy SOFT conversion using default palette, white background and Floyd-Steinberg dithering. Alpha threshold is 16.
Using ConvertPixelFormat with Indexed8 format, SystemDefault8BppPalette quantizer (white background, alpha threshold = 16) and Floyd-Steinberg dithering. The bottom 16 rows are transparent, the alpha pixels above were blended with white.

Alpha gradient converted to indexed 8 bit format by FormatConvertedBitmap
Using WPF's FormatConvertedBitmap with the same parameters as above. The result is forcibly dithered and the alpha pixels above the threshold were not blended with any back color so the vertical gradient has been just disappeared.

Shield icon with transparent background
Shield icon with transparency

Shield icon converted to BGR555 format with black background and Floyd-Steinber dithering
Using ConvertPixelFormat with Bgr555 format, Rgb555 quantizer with default parameters (so the background is black) and Floyd-Steinberg dithering.

Shield icon converted to BGR555 format by FormatConvertedBitmap
Using WPF's FormatConvertedBitmap with Bgr555 format. The alpha pixels were just turned opaque without blending them with any color so some light pixels appeared where RGB values of the alpha pixels were not completely black. As FormatConvertedBitmap does not use dithering for this pixel format, the result has a quite noticeable banding.

Information icon with transparent background
Information icon with transparency

Information icon converted to Indexed2 format with Wu quantizer using silver background and Bayer 8x8 dithering
Using ConvertPixelFormat with Indexed2 format, Wu quantizer (with 4 colors, silver background, alpha threshold = 16) and Bayer 8x8 dithering.

Information icon converted to Indexed2 format by FormatConvertedBitmap
Using WPF's FormatConvertedBitmap with Indexed2 format without specifying a palette so it was optimized by FormatConvertedBitmap. The alpha pixels above the threshold were not blended by any back color so the black shadow just consists of the original pixels after removing alpha. A default dithering was automatically applied.

Exceptions

ArgumentNullExceptionbitmap is .
ArgumentOutOfRangeExceptionnewPixelFormat does not specify a valid format.
ArgumentExceptionThe quantizer palette contains too many colors for the indexed format specified by newPixelFormat.
InvalidOperationExceptionA deadlock has been detected while attempting to create the result.

See Also